CodeIgniter Basic Tutorial
Performance & Utilities
CodeIgniter Advanced
Cookies are small pieces of data stored on the client’s browser. In CodeIgniter, cookies can be used to remember user preferences, login details, or short-lived data.
CodeIgniter provides easy helper functions for managing cookies without writing raw PHP code.
Example use cases:
Before working with cookies, load the cookie helper.
In application/config/autoload.php
:
$autoload['helper'] = array('cookie');
Or load it manually in your controller:
$this->load->helper('cookie');
CodeIgniter provides the set_cookie()
function.
$cookie = array( 'name' => 'username', 'value' => 'JohnDoe', 'expire' => 3600, // 1 hour 'secure' => FALSE // TRUE if using HTTPS ); $this->input->set_cookie($cookie);
👉 Shortcut method:
set_cookie('username', 'JohnDoe', 3600);
Use get_cookie()
to read a cookie.
echo get_cookie('username'); // Output: JohnDoe
Use delete_cookie()
to remove a cookie.
delete_cookie('username');
class CookieController extends CI_Controller { public function set() { // Set cookie for 2 minutes set_cookie('user', 'CodeIgniter Learner', 120); echo "Cookie has been set!"; } public function get() { $user = get_cookie('user'); if ($user) { echo "Welcome back, " . $user; } else { echo "No cookie found!"; } } public function delete() { delete_cookie('user'); echo "Cookie deleted!"; } }