CodeIgniter Cookie Management

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:

  • Remembering a logged-in user’s session ID.
  • Storing user preferences like theme or language.
  • Temporary tracking data for analytics.


🔹 Step 1: Load Cookie Helper

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');


🔹 Step 2: Setting a Cookie

CodeIgniter provides the set_cookie() function.

Example:

$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);


🔹 Step 3: Retrieving a Cookie

Use get_cookie() to read a cookie.

echo get_cookie('username');  
// Output: JohnDoe


🔹 Step 4: Deleting a Cookie

Use delete_cookie() to remove a cookie.

delete_cookie('username');


🔹 Example: Controller Using Cookies

Controller (CookieController.php)

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!";
    }
}



Whereisstuff is simple learing platform for beginer to advance level to improve there skills in technologies.we will provide all material free of cost.you can write a code in runkit workspace and we provide some extrac features also, you agree to have read and accepted our terms of use, cookie and privacy policy.
© Copyright 2024 www.whereisstuff.com. All rights reserved. Developed by whereisstuff Tech.