As a CodeIgniter developer, it’s really important for you to understand how to work with the core session library. Of course, you could always use the default $_SESSION syntax.
If you want to work with sessions in CodeIgniter, the first thing you’ll need is a built-in session library. While that’s not the case most of the time, you can autoload the session library in CodeIgniter so that it enables session handling features for every web request. You may also like How to create flash messages in Codeigniter and How to Ajax Pagination in Codeigniter.
Steps For How to Session Management in Codeigniter
Step 1: Initializing a Session
In this step open the file located at application/config/autoload.php
$autoload['libraries'] = array('session');
Also, You can use the following code somewhere in your controller file to load the session library.
Step 2: Add Session Data
In Codeiginter, we simply use array to set any data in session as shown below.
$userdata = array( 'username' => 'alex', 'email' => '[email protected]', 'logged_in' => TRUE ); $this->session->set_userdata($userdata);
Step 3: Fetch Session Data
After setting data in session, we can also retrieve that data as shown below.
$username = $this->session->userdata('username');
Step 4: Remove Session Data
Removing session data in CodeIgniter is very simple as shown below. The below version of unset_userdata() function will remove only one variable from session.
If you want to remove more values from session or to remove an entire array you can use the below version of unset_userdata() function.
$userdata = array( 'username' => 'alex', 'email' => '[email protected]', 'logged_in' => TRUE ); $this->session->unset_userdata($userdata);