Home >>Codeigniter Tutorial >How to Set Session in Codeigniter With Example

How to Set Session in Codeigniter With Example

How to Set Session in Codeigniter With Example

Keep track of the user details and what is the state of the user is completely done using sessions. The session maintains the user state and tracks their activity.

Maintaining the state helps in preserving the next request from the previous one. Users don’t have to log in for each page, they can log in once and their details are stored in a session with a session id of that user and then that same data is reused for further request.

Codeigniter has a built-in class names ‘session’ for this purpose. The same purpose of this session is to make the data available for the next request made by the user.

Session Working:

When a page is requested by a user, the session class on the server checks whether the cookie sent by the browser is valid or not. If the session cookie is not valid or not available (expired or session expired) a new session is created.

If there is a valid session, it will be automatically updated with the session id. The session runs automatically once initialization is done. From reading, writing, and updating session everything is automatic.

Session Initialization

With each page request/load on the site, session are globally run but to use the data the initialization of session is done on the controller constructors or can be auto-loaded in the system by session up ‘session’ in autoload.php

Inside your controller you can load session by using this line of code:

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

OR in application/config/autoload.php file add session library to autoload

$autoload['libraries'] = array(‘session’);

After the initialization of the session or loading session library, its object is available using.

$this->session

Retrieval of Session Data

$_SESSION is a super-global used to avail information from a session array. For fetching any piece of information we can simply use $_SESSION[‘item’]

In Codeigniter using magic method i.e.

 $this->session->item

OR by using userdata() method which takes the parameter to be retrieved like this:

$this->session->userdata('item');

Session can be retrieved and stored inside a variable like this:

$var = $this->session->item; 
OR
$var = $this->session->userdata('item');

To get all existing userdata no parameters are passed in the method.

$this->session->userdata();

Note : Userdata() method returns NULL if no item is found.

Adding of Session Data :

Adding a session data help out in making data globally available without running the DB query every time.

Session data can be added in key-value pairs like $_SESSION['name']='abc';

In Codeigniter it can be simply done using set_userdata(). It can be done in two ways passing one value at a time or passing an associative array to it like as shown below:

Passing one value at a time:

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

Passing associative array inside:

$array = array(
'name' => 'believemaster',
'email' => 'believemasters@gmail.com'
);
$this->session->set_userdata($array);

where $array is associative array above containing data.For verifyin the session value existence has_userdata() is used

 $this->session->has_userdata(‘value’);

Removing of Sessoin Data :

In Codeigniter just as set_userdata() method for adding session data there is method called unset_userdata() for removing session data by passing the session key.

If you want to remove name from the session which is a key value for the session you can do it as:

$this->session->unset_userdata('name');

Unsetting the session can also be done in array format with the item key to unset like this:

$array_list = (
'name',
'email'
);	
$this->session->unset_userdata($array_list);

Session FlashData :

Session availability for only the next request and clearing it out automatically after that is done using flash data. This is mostly used to show one-time information i.e. error/success messages, information/status messages, etc.

In Codeigniter set_flashdata() method is available for setting up session available for next request only. It requires two parameters key and value associated to that.

$this->session->set_flashdata('error', 'You have an error');
$this->session->set_flashdata('success', 'Successful');

An array can also be passed as parameter in set_flashdata()

To call the flash data, flashdata('key') method is used with a key_item passing in the parameters to call specific flash-data or call flashdata() without parameter to call all flashdata.

$this->session->flashdata('error');		// specific flashdata
$this->session->flashdata();			// all flashdata

For keeping flashdata for further request keep_flashdata() method is used. Single key_item or an array can be passed as parameters.

$this->session->keep_flashdata('success');
$this->session->keep_flashdata(array('error', 'success'));

Simple Example Code for Session (using session flash data):

Create SessionController application/controller/SessionController.php

<?php 
class SessionController extends CI_Controller
{
public function __construct()
{
parent:: __contstruct();

$this->load->helper('url');
$this->load->libraries('session');
}
public function index()
{
$this->load->view('index');
}

public function flash()
{
$this->session->set_flashdata('sess', 'session message');
redirect(base_url('index.php/SessionController/index'));
}
}
?>

Create Index View : application/views/index.php

<html>
    <head>
        <title>CI Session Flash Data</title>
    </head>
    <body>
     <p>The session value of session is 
	     <b><?php echo $this->session->flashdata('sess');?></b>
	   </p>
    </body>
</html>

No Sidebar ads