Handling session in CodeIgniter

By | July 30, 2015

Handling session in CodeIgniter

A session is a way to save information on a variable which is to be used across other pages in the same domain. The session is stored in the server side.

CodeIgniter handles the session with a session class with as a library. The session class is used to store a users state and track their activity. The session class
stores information for each users as a serialized data in a cookie. In CodeIgniter the session can also be stored in database.

In Codeigniter, the session class wont utilize native PHP session. It creates its own to provide more flexibility.

Initialize a Session

The session class can be initialized in your controller constructor or by can be autoloaded in the application/config/autoload.php file.

Because we are not sure in which page we are going to use session and we need session data available to all the pages, i prefer
autoloading the session library is feasable.

If you want to manuall include the session library in your controller, then you can use the following code

Session Data

Session Data in CodeIgniter is nothing but an array of information stored in it. By default, CodeIgniter Session will have the following datas in its session

– The user’s unique Session ID
– The user’s IP Address
– The user’s User Agent data
– The “last activity” time stamp.

Retrieve a session data

In CodeIgniter retrieving session data is much simple. By using the below code you can retrieve an item from the session data

To retrive all the session data we can use,

Adding a session data
To add a item to the session array, we can use the set_userdata() function of the CodeIgniter Session library class,

You can also passs an array of items to it,

Removing a session data

To remove a session data from the session array,

You can pass the argument as a variable or as a array

Destroying a Session

To destroy the current session:


Leave a Reply