counter customizable free hit

Session Data in CodeIgniter


In this tutorial we’re going to go over the Session class in CodeIgniter (CI). The Session class is responsible for initializing session cookies, setting session data, and returning session data when it’s called in your application. We’ll be creating the session, creating session data, and then reading session data from our session cookie.

Session Configuration

First we want to initialize a session cookie, we’re going to do this in autoload.php on line 55:

Now our session cookie is autoloaded globally across the app.

Next, we’re going to make sure our session cookies are encrypted. Navigate to config.php and change the following to TRUE on line 250:

Don’t forget to set your encryption key on line 227 otherwise you’ll get a fatal error when you run your application.

The Controller

We’re going to edit the default welcome controller to pass the session id to a view named data:

The View

Now that we have a controller pulling the session id from our cookie we want to view that data in the browser to ensure that our session class is working properly. We can do that by creating a view called data.php and then echo out the variable $id which will contain our session id.

Write the following in the data.php view:

If you view your app in your browser you’ll see the session id displayed on the web page. Awesome! we have a working session cookie and we can look up the session data from within our app, but how do we add data to our session cookie?

Adding Session Data

We’re going to add some session data to the session cookie, so go back to the welcome.php controller and make it look like this:

You can see we’re passing a username into the $sessionData array named user, then we assign our session ‘username’ to our $data array with the same ‘username’ key.

Now that we’re passing the username into our view through the $data array, we need to display it in the view, so go into data.php and write the following:

Now when you open your application in the browser you’ll see your session id and the username user.


We’ve learned how to create session cookies, query session data, and set session data in this CodeIgniter tutorial. These skills will help you create dynamic user-centric web applications.

Leave a Reply