CodeIgniter Libraries

CodeIgniter libraries help you do your job faster and more efficiently. Each library is really a PHP class with various methods that you can use once the library is loaded by a controller. Some classes are so useful and so ubiquitous that you might as well autoload them (such as the database and session libraries).

The session library

Retrieving Session Data

Any piece of information from the session array is available using the following function:


Where item is the array index corresponding to the item you wish to fetch. For example, to fetch the session ID you will do this:

$session_id = $this->session->userdata('session_id');

Adding Custom Session Data

A useful aspect of the session array is that you can add your own data to it and it will be stored in the user's cookie. Why would you want to do this? Here's one example:

Let's say a particular user logs into your site. Once authenticated, you could add their username and email address to the session cookie, making that data globally available to you without having to run a database query when you need it.

To add your data to the session array involves passing an array containing your new data to this function:


Where $array is an associative array containing your new data. Here's an example:

$newdata = array(
                   'username'  => 'johndoe',
                   'email'     => '',
                   'logged_in' => TRUE


If you want to add userdata one value at a time, set_userdata() also supports this syntax.

$this->session->set_userdata('some_name', 'some_value');

See the original documentation page.

Learning Resources

See the original documentation page.

Post A Comment

Anti-Spam Quiz: