How to Work With Session Data in CodeIgniter

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, but it’s always recommended to use the wrapper instead.

Starting with how to load a session library, we’ll move to the discussion of how to add, retrieve, remove and destroy session variables. In the last segment, we’ll have a look at the different built-in session drivers at your disposal provided by the CodeIgniter framework itself.

How to Load a Session Library

If you want to work with sessions in CodeIgniter, the first thing you’ll need is a built-in session library. Unless and until you develop a web application that doesn’t require sessions at all, you shouldn’t bother about the 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.

Go ahead and open the file located at application/config/autoload.php. Find the following section.

/*
| -------------------------------------------------------------------
|  Auto-load Libraries
| -------------------------------------------------------------------
| These are the classes located in system/libraries/ or your
| application/libraries/ directory, with the addition of the
| 'database' library, which is somewhat of a special case.
|
| Prototype:
|
|    $autoload['libraries'] = array('database', 'email', 'session');
|
| You can also supply an alternative library name to be assigned
| in the controller:
|
|	$autoload['libraries'] = array('user_agent' => 'ua');
*/
$autoload['libraries'] = array();

The $autoload['libraries'] array holds the list of libraries that need to be autoloaded. As per our requirement, let’s change it to look like this:

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

Also, there’s another way you could have achieved that. You can use the following code somewhere in your controller file to load the session library.

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

That’s pretty much it as far as initialization of the session library is concerned.

In the next couple of sections, we’ll go through the different operations that you can do with the core session library. To demonstrate it, we’ll build an example controller file that loads the session library and provides methods that will be discussed throughout this article.

Go ahead and create a file application/controllers/Example.php with the following contents.

<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Example extends CI_Controller {
    public function __construct()
    {
        parent::__construct();

        // load Session Library
        $this->load->library('session');
        
        // load url helper
        $this->load->helper('url');
    }

    public function index()
    {
        /**** SET SESSION DATA ****/
        // set single item in session
        $this->session->set_userdata('favourite_website', 'http://tutsplus.com');
        
        // set array of items in session
        $arraydata = array(
                'author_name'  => 'Sajal Soni',
                'website'     => 'http://code.tutsplus.com',
                'twitter_id' => '@sajalsoni',
                'interests' => array('tennis', 'travelling')
        );
        $this->session->set_userdata($arraydata);
        
        /**** GET SESSION DATA ****/
        // get data from session
        echo "Favourite Website: ". $this->session->userdata('favourite_website');
        echo "<br>";
        echo "Author Name: ". $this->session->userdata('author_name');
        echo "<br>";
        echo "Interest (Array Example): " . $this->session->userdata('interests')[0];
        echo "<br>";
    
        // get e'thing stored in session at once
        echo '<pre>';
        print_r($this->session->userdata());
        
        /**** REMOVE SESSION DATA ****/
        // unset specific key from session
        $this->session->unset_userdata('favourite_website');
        
        // unset multiple items at once
        $keys = array('twitter_id', 'interests');
        $this->session->unset_userdata($keys);
    
        echo '<pre>';
        print_r($this->session->userdata());
    }
    
    public function setflash()
    {
        // set flash data
        $this->session->set_flashdata('flash_welcome', 'Hey, welcome to the site!');
        
        // mark existing data as flash data
        $this->session->set_userdata('flash_message', 'I am flash message!');
        $this->session->mark_as_flash('flash_message');
        
        redirect('example/getflash');
    }
    
    public function getflash() 
    {
        // get flash data
        echo "Flash welcome message: ". $this->session->flashdata('flash_welcome');
        echo '<pre>';
        print_r($this->session->flashdata());
    }

    public function tempdata() 
    {
        // set temp data
        $this->session->set_tempdata('coupon_code', 'XYEceQ!', 300);

        // mark existing data as temp data
        $this->session->set_userdata('coupon_code', 'XYEceQ!');
        $this->session->mark_as_temp('coupon_code', 300);
        
        // get temp data
        echo $this->session->tempdata('coupon_code');
    }

    public function destroy()
    {
        $this->session->set_userdata('favourite_website', 'http://tutsplus.com');
        
        // destory session
        $this->session->sess_destroy();
    }
}

That’s a very basic controller file you should be familiar with as a CodeIgniter developer. Now, we’re ready to move to the next couple of sections that provide insight into the session handling concepts.

How to Add, Retrieve and Remove Session Data

To start with, let’s fetch the code of our __construct method.

public function __construct()
{
    parent::__construct();

    // load Session Library
    $this->load->library('session');
    
    // load url helper
    $this->load->helper('url');
}

Just in case you haven’t autoloaded the session library, it’ll do that in the first place. Apart from that, we’ve also loaded the url helper that allows us to use certain utility methods that we’ll see later.

Next, grab the code of the index method.

public function index()
{
    /**** SET SESSION DATA ****/
    // set single item in session
    $this->session->set_userdata('favourite_website', 'http://tutsplus.com');
    
    // set array of items in session
    $arraydata = array(
            'author_name'  => 'Sajal Soni',
            'website'     => 'http://code.tutsplus.com',
            'twitter_id' => '@sajalsoni',
            'interests' => array('tennis', 'travelling')
    );
    $this->session->set_userdata($arraydata);
    
    /**** GET SESSION DATA ****/
    // get data from session
    echo "Favourite Website: ". $this->session->userdata('favourite_website');
    echo "<br>";
    echo "Author Name: ". $this->session->userdata('author_name');
    echo "<br>";
    echo "Interest (Array Example): " . $this->session->userdata('interests')[0];
    echo "<br>";

    // get e'thing stored in session at once
    echo '<pre>';
    print_r($this->session->userdata());
    
    /**** REMOVE SESSION DATA ****/
    // unset specific key from session
    $this->session->unset_userdata('favourite_website');
    
    // unset multiple items at once
    $keys = array('twitter_id', 'interests');
    $this->session->unset_userdata($keys);

    echo '<pre>';
    print_r($this->session->userdata());
}

As you’ve loaded the session library already, you can use $this->session to access the session object and access the methods that are supported. The set_userdata method is used to create a new session variable, and generally it takes two arguments—key and value.

$this->session->set_userdata('favourite_website', 'http://tutsplus.com');

You can also use the set_userdata method to create multiple variables in a single call. In that case, you just need to provide one argument, and it should be an array as shown below.

// set array of items in session
$arraydata = array(
        'author_name'  => 'Sajal Soni',
        'website'     => 'http://code.tutsplus.com',
        'twitter_id' => '@sajalsoni',
        'interests' => array('tennis', 'travelling')
);
$this->session->set_userdata($arraydata);

Users with sharp eyes would have noticed that you could also assign an array as a value of any session variable, as shown above in the interests example.

Now, let’s see how to retrieve the value of any session variable. The userdata method is used to retrieve the value of any session variable, and usually it needs the key of the session variable that you’re looking for as the first argument.

echo "Favourite Website: ". $this->session->userdata('favourite_website');

If you’re looking for one of the array entries, you can use the following:

echo "Interest (Array Example): " . $this->session->userdata('interests')[0];

More often than not, you want to know how many variables in total are stored in an active session for debugging purposes, and you can do that as well.

// get e'thing stored in session at once
echo '<pre>';
print_r($this->session->userdata());

Yes, the same userdata method comes to our rescue! If you don’t pass any argument to the userdata method, it’ll return all the session variables.

Finally, let’s see how you can remove variables from the session. It’s the unset_userdata method that you can use should you want to remove any session entries.

// unset specific key from session
$this->session->unset_userdata('favourite_website');

And here’s the variation of the same method that shows how to remove multiple entries in a single go.

// unset multiple items at once
$keys = array('twitter_id', 'interests');
$this->session->unset_userdata($keys);

And that should delete the twitter_id and interests entries from the session.

Go ahead and test the index method to see things in action.

Useful Goodies: Flashdata and Tempdata

In the last section, we discussed the basics of session handling in CodeIgniter. In this section, we’ll discuss couple of other utility methods provided by the session library.

In your day-to-day development, you often need to display messages in response to certain user actions. As an example, you want to display a success message when someone posts a comment on your site, and the message should be displayed only once. The set_flashdata method is a perfect candidate for this kind of use case.

In fact, set_flashdata is very similar to the set_userdata method in that it allows you to save a value in session. The only exception is that the session value set by the flashdata method is available for the next request only. In subsequent requests, you won’t be able to access these variables anymore as they were cleared.

Grab the code of the setflash method.

public function setflash()
{
    // set flash data
    $this->session->set_flashdata('flash_welcome', 'Hey, welcome to the site!');
    
    // mark existing data as flash data
    $this->session->set_userdata('flash_message', 'I am flash message!');
    $this->session->mark_as_flash('flash_message');
    
    redirect('example/getflash');
}

You can create a new flashdata variable in the same way you would have created a regular session variable using the set_userdata method. On the other hand, you can also mark an existing session variable as a flashdata variable. In that case, you need to use the mark_as_flash method, as shown in the above code.

Finally, we redirect the user to the getflash method that shows how to use flashdata variables that were set in the setflash method. Let’s have a quick look at the getflash method.

public function getflash() 
{
    // get flash data
    echo "Flash welcome message: ". $this->session->flashdata('flash_welcome');
    echo '<pre>';
    print_r($this->session->flashdata());
}

As expected, there’s a flashdata method that allows you to fetch session variables stored as flashdata. If you call the flashdata method without any arguments, it’ll return all flashdata variables similar to that of the userdata method.

Go ahead and test the setflash method. You’ll be redirected to the getflash URL, and you’ll see the message. If you refresh the getflash page, you won’t see that message again!

Next, there’s another variation provided by the session library in this category—the tempdata session variables. If you want to create session variables for a specific time period, the set_tempdata method is the one you’re looking for.

For example, if you want to create a session variable that should be automatically deleted after a certain time period, you can use the set_tempdata method to create such a variable, as shown in the following method.

public function tempdata() 
{
    // set temp data
    $this->session->set_tempdata('coupon_code', 'XYEceQ!', 300);

    // mark existing data as temp data
    $this->session->set_userdata('coupon_code', 'XYEceQ!');
    $this->session->mark_as_temp('coupon_code', 300);
    
    // get temp data
    echo $this->session->tempdata('coupon_code');
}

The third argument in the set_tempdata method indicates the number of seconds after which the variable will be deleted from the session.

You can also mark an existing session variable as tempdata using the mark_as_temp method provided that you’ve already created a session variable using the set_userdata method.

Finally, you can use the tempdata method to fetch the value of any tempdata variable.

So it’s nice to have such utility methods at your disposal in your day-to-day development lifecycle!

What You Should Not Forget: Session Destroy

Destroying the session is probably the last thing you would like to do when the user logs out. It makes sure that the session variables set so far are deleted from the active session and are no longer available for subsequent requests.

Let’s pull in the code of the destroy method and go through it.

public function destroy()
{
    $this->session->set_userdata('favourite_website', 'http://tutsplus.com');
    
    // destroy session
    $this->session->sess_destroy();
}

It’s the sess_destroy method that helps us to destroy the active session. Of course, it’ll also delete tempdata and flashdata variables that were set in the active session.

Make sure you get yourself into the habit of destroying a session once it’s no longer useful in the current user context.

Cherry on the Top: Session Drivers

We’re into the last section of this article—the session drivers. More often than not, you don’t bother about configuring the session driver in your application as the default session driver, the file system, is configured already with the default setup.

So it’s the file system that holds all session-related data, and it’s widely used and is the accepted standard for session handling. Having said that, CodeIgniter also supports other session drivers that you could use should you wish to switch from the default file system session driver.

Here’s a list of all supported session drivers in CodeIgniter:

  • Files
  • Database
  • Redis
  • Memcached

The database session driver, as the name suggests, stores the session data in the database that you’ve configured for your CodeIgniter application.

On the other hand, the other two session drivers are in-memory storage mechanisms preferred for high-performance websites.

In the application/config/config.php file, you can configure the session driver that you would like to use in your application.

$config['sess_driver'] = 'database';
$config['sess_save_path'] = 'custom_sessions';

It tells CodeIgniter to use the database session driver, and the session data will be saved in the custom_sessions MySQL table.

Discussion of each and every session driver is beyond the scope of this article, but you can go through the official site documentation that provides an in-depth guide for each driver.

Conclusion

Session handling in CodeIgniter was the topic of today’s tutorial, and we discussed it thoroughly by looking at every aspect of the subject.

Starting with basic session operations, we also went through those cool flashdata and tempdata methods, and it was the discussion of session drivers that concluded our article.

As always, you could shout out your queries and suggestions using the feed below!

Leave a Reply

Your email address will not be published. Required fields are marked *