In this tutorial we will learn about CodeIgniter Session Management. When building websites, we often have to track user activity and status and we have to use session for this purpose. For this purpose, CodeIgniter has a session class.

CodeIgniter Session Initialization

Data for sessions are available worldwide through the site, but for the first time we need to initialize the session. We can do that by running the next line in the constructor.

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

You can simply use the session object as shown below after you have loaded the session library.

$this->session

Add CodeIgniter Session Data

We simply use the “$_SESSION” array in PHP to set any session data as shown below.

$_SESSION['key'] = value;

Where ‘key’ is the array and the value is assigned to the ‘key’.┬áIn CodeIgniter you can do the same thing as shown below.

$this->session->set_userdata('some_name', 'some_value');

The function set_userdata() takes two arguments.

The first argument, some name, is the name of the variable session, under which some value is stored.

The set_userdata() function also supports another syntax that allows you to pass array values to store as shown below.

$newdata = array( 
   'username'  => 'editor', 
   'email'     => 'editor@tutorialpace.com', 
   'logged_in' => TRUE
);  

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

Remove CodeIgniter Session Data

In PHP, the session data can be deleted using the unset() function as shown below.

unset($_SESSION['some_name']);

It is very easy to remove session data in CodeIgniter as shown below. The version below of the function unset_userdata() will remove only one variable from the session.

$this->session->unset_userdata($array_items);

Fetch CodeIgniter Session Data

After setting the session data, we can also get the data as shown below. For this purpose, the Userdata() function is used. This function returns NULL if the information you want to access is not available.

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