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.

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:

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.

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.

Leave a Comment

Scroll to Top