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.
$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.
Let’s say a particular user logs into your site. Once authenticated, you could add their username and e-mail address to the session, making that data globally available to you without having to run a database query when you need it.
You can simply assign data to the
$_SESSION array, as with any other variable. Or as a property of
Alternatively, the old method of assigning it as “userdata” is also available. That however passing an array containing your new data to the
$array is an associative array containing your new data. Here’s an example:
If you want to add userdata one value at a time,
set_userdata() also supports this syntax:
If you want to verify that a session value exists, simply check with
Or you can call
Just as with any other variable, unsetting a value in
$_SESSION can be done through
Also, just as
set_userdata() can be used to add information to a session,
unset_userdata() can be used to remove it, by passing the session key. For example, if you wanted to remove ‘some_name’ from your session data array:
This method also accepts an array of item keys to unset:
When a page is loaded, the session class will check to see if valid session cookie is sent by the user’s browser. If a sessions cookie does notexist (or if it doesn’t match one stored on the server or has expired) a new session will be created and saved.
If a valid session does exist, its information will be updated. With each update, the session ID may be regenerated if configured to do so.
It’s important for you to understand that once initialized, the Session class runs automatically. There is nothing you need to do to cause the above behavior to happen. You can, as you’ll see below, work with session data, but the process of reading, writing, and updating a session is automatic.
Required fields are marked *
Get all latest content delivered to your email free.