CodeIgniter Session

CI Session Class track information about each user while they browse site.Ci Session class generates its own session data, offering more flexibility for developers.

Initializing a Session

To initialize the Session class manually in our controller constructor use following code.


Adding Custom Session Data

We can add our custom data in session array.To add our data to the session array involves passing an array containing your new data to this function.


Where $newarray is an associative array containing our new data.

$newarray = array(
                   'name'  => 'manish',
                   'email'     => '[email protected]');

Retrieving Session

We can retrieve any piece of information from the session array with following code.

$session_id = $this->session->userdata('session_id');

Above function returns FALSE (boolean) if the session array does not exist.

Retrieving All Session Data

To Retrieve all userdata use following function.


Above function return an associative array like the following.

    [session_id] => 4a5b5dca45708ab1a84364eeb455j007
    [ip_address] =>
    [user_agent] => Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_7;
    [last_activity] => 1102132923

Removing Session Data

unset_userdata() is used to unset session data.For example, if you wanted to remove 'some_data' from your session data.


We can also used an associative array of items to unset session data.

$session_array = array('fname' => '', 'email' => ''); $this->session->unset_userdata(session_array);

Destroying Session

We use this function to remove the current session.


If we want to destroy some items and not all, use unset_userdata().

Ci Session Example

Below Example shows how to set and retrieve session in CI

Step 1

First we create Controller file inside application/controllers/cisession.php to set session data.

class cisession extends CI_Controller{
  function __construct()


function index()

$sessiondata = array(
                   'name'  => 'manish',
                   'email'     => '[email protected]',
Step 2

Create view files inside application\views\cisession.php to retrieve session data.

<title>Codeigniter Session Example  </title>
<h3>Retrieve session data </h3>
$session_id = $this->session->userdata('sessiondata');