For any queries you can reach us at / WhatsApp us: +919158876092

Session in CodeIgniter 4


The Session class allows you to maintain a user’s "state" and track their activity while they browse your site.

Session Initialization

To access and initialize the session:

$session = \Config\Services::session($config);


$this->session 	= \Config\Services::session();

Add data to the session

set() method is used to add value to the session. It takes two arguments as a parameter first is session name and the second is session value.

$this->session->set('session_name', 'any_value');

We can also use the set() function to pass an array to store values as shown below.

$data = array(
	'username' 	=> 'infovistar',
	'email' 	=> '',
	'logged_in'	=> TRUE

Fetch data from Session

A get() function is used to get data from the session. It takes the session key name as an argument. For example:

$name = $this->session->get('username');

Remove data from Session

We can use remove() function that will remove data from the session.


If you want to remove more that one value and an array data then you can use the same function remove().

$data = array('username', 'email');

Destroying a Session

To clear the current session (for example, during a logout), you may simply use either PHP’s session_destroy() function, or the library’s destroy() method. Both will work in exactly the same way:


// or



While building a web application, we need to store some data for only one time, and later, we want to remove that data. For example, to display some error message or information message. In CodeIgniter, flashdata will only be available until the next request, and it will get deleted automatically.

Add Flashdata:


You can also pass an array to setFlashdata(), in the same manner as set().

$data = array(
	'username' 	=> 'infovistar',
	'email' 	=> ''

Retrieve Flashdata:


Or to get an array with all flashdata, simply omit the key parameter: