CodeIgniter Session Tutorial (GET, SET & DESTROY Session Data)

On 9/05/2016

CodeIgniter Session Tutorial: This post will show you how to start and destroy session in codeigniter. Sessions are used to maintain user's state and keep track of their activity on your website. Every user is associated with a unique session ID which will then be stored in a session cookie. But for additional security you can store sessions in database and verify the session id from the cookie against the one from DB.

CodeIgniter's Session class takes care of session related tasks effectively. For each session it stores by default some basic details like session_id, user ip address but also permits to set custom data in sessions.


To Start Session in CodeIgniter:

In order to start session in code igniter first you'll need to initialize the session class and set userdata. You can either do it by auto-loading session class inside application/config/autoload.php or load it individually in your controller.


Once loaded you get to access it through the handle $this->session.

CodeIgniter: Set Session Data

Using the method set_userdata() you can set session data in codeignitor. Again you can use two different ways to store data in session.

You can set multiple items at once using associative array. For example at the time of user login you may need to store several details about a user which you can set it as an array like this,

$data = array(
    'id' => 'UX102900',
    'name' => 'Kevin',
    'email' => ''


Or set userdata as one variable at a time,

$this->session->set_userdata('name', 'Jackson');

CodeIgniter: Get session data

To get/retrieve data which is already stored in session use,


The function returns FALSE if you try to access a session key that does not exist.

To retrieve all session data at once use the method,


Delete Session Data

Just like setting session data, you can unset them using unset_userdata() function while the session is still alive.

To delete one session variable at a time use,


To delete multiple items at once pass the session keys as an array to unset_userdata() like this,

$data = array(
    'name' => '',
    'email' => ''


Destroy Session in CodeIgniter

Use the method sess_destroy() to clear the current session.


Once you run this, all your userdata will be cleared out and you won't get to access them and not even flashdata. So make sure to call it as the final step like when user logs out of the site.

That explains about handling sessions in codeigniter. Just make sure to set encryption key in config.php file even if you don't intend to use encrypted sessions. This will keep away the hackers from manipulating session data.

No comments:

Post a Comment

Contact Form


Email *

Message *