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.

$this->load->library('session');

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.

$this->session->set_userdata($newarray);

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

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

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.

$this->session->all_userdata()

Above function return an associative array like the following.

Array
(
    [session_id] => 4a5b5dca45708ab1a84364eeb455j007
    [ip_address] => 127.0.0.1
    [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.

$this->session->unset_userdata('some_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.

$this->session->sess_destroy();

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.

<?php
class cisession extends CI_Controller{
  function __construct()
{

parent::__construct();
}

function index()
  {

$sessiondata = array(
                   'name'  => 'manish',
                   'email'     => '[email protected]',
                  
               );
$this->session->set_userdata('sessiondata',$sessiondata);
$this->load->view('cisession');
  }
}
?>
Step 2

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

<html>
<head>
<title>Codeigniter Session Example  </title>
</head>
<body>
<h3>Retrieve session data </h3>
<?php
$session_id = $this->session->userdata('sessiondata');
print_r($session_id);
?>
</body>
</html>