Session Library

The Session class permits you to maintain a user’s “state” and track theiractivity while they browse your site.

CodeIgniter comes with a few session storage drivers, that you can seein the last section of the table of contents:

Using the Session Class

Initializing a Session

Sessions will typically run globally with each page load, so the Sessionclass should be magically initialized.

To access and initialize the session:

  1. $session = \Config\Services::session($config);

The $config parameter is optional - your application configuration.If not provided, the services register will instantiate your defaultone.

Once loaded, the Sessions library object will be available using:

  1. $session

Alternatively, you can use the helper function that will use the defaultconfiguration options. This version is a little friendlier to read,but does not take any configuration options.

  1. $session = session();

How do Sessions work?

When a page is loaded, the session class will check to see if a validsession cookie is sent by the user’s browser. If a sessions cookie doesnot exist (or if it doesn’t match one stored on the server or hasexpired) a new session will be created and saved.

If a valid session does exist, its information will be updated. With eachupdate, the session ID may be regenerated if configured to do so.

It’s important for you to understand that once initialized, the Sessionclass runs automatically. There is nothing you need to do to cause theabove behavior to happen. You can, as you’ll see below, work with sessiondata, but the process of reading, writing, and updating a session isautomatic.

Note

Under CLI, the Session library will automatically halt itself,as this is a concept based entirely on the HTTP protocol.

A note about concurrency

Unless you’re developing a website with heavy AJAX usage, you can skip thissection. If you are, however, and if you’re experiencing performanceissues, then this note is exactly what you’re looking for.

Sessions in previous versions of CodeIgniter didn’t implement locking,which meant that two HTTP requests using the same session could run exactlyat the same time. To use a more appropriate technical term - requests werenon-blocking.

However, non-blocking requests in the context of sessions also meansunsafe, because, modifications to session data (or session ID regeneration)in one request can interfere with the execution of a second, concurrentrequest. This detail was at the root of many issues and the main reason whyCodeIgniter 4 has a completely re-written Session library.

Why are we telling you this? Because it is likely that after trying tofind the reason for your performance issues, you may conclude that lockingis the issue and therefore look into how to remove the locks …

DO NOT DO THAT! Removing locks would be wrong and it will cause youmore problems!

Locking is not the issue, it is a solution. Your issue is that you stillhave the session open, while you’ve already processed it and therefore nolonger need it. So, what you need is to close the session for thecurrent request after you no longer need it.

  1. $session->destroy();

What is Session Data?

Session data is simply an array associated with a particular session ID(cookie).

If you’ve used sessions in PHP before, you should be familiar with PHP’s$_SESSION superglobal(if not, please read the content on that link).

CodeIgniter gives access to its session data through the same means, as ituses the session handlers’ mechanism provided by PHP. Using session data isas simple as manipulating (read, set and unset values) the $_SESSIONarray.

In addition, CodeIgniter also provides 2 special types of session datathat are further explained below: flashdata and tempdata.

Retrieving Session Data

Any piece of information from the session array is available through the$_SESSION superglobal:

  1. $_SESSION['item']

Or through the conventional accessor method:

  1. $session->get('item');

Or through the magic getter:

  1. $session->item

Or even through the session helper method:

  1. session('item');

Where item is the array key corresponding to the item you wish to fetch.For example, to assign a previously stored ‘name’ item to the $namevariable, you will do this:

  1. $name = $_SESSION['name'];
  2.  
  3. // or:
  4.  
  5. $name = $session->name
  6.  
  7. // or:
  8.  
  9. $name = $session->get('name');

Note

The get() method returns NULL if the item you are tryingto access does not exist.

If you want to retrieve all of the existing userdata, you can simplyomit the item key (magic getter only works for single property values):

  1. $_SESSION
  2.  
  3. // or:
  4.  
  5. $session->get();

Adding Session Data

Let’s say a particular user logs into your site. Once authenticated, youcould add their username and e-mail address to the session, making thatdata globally available to you without having to run a database query whenyou need it.

You can simply assign data to the $_SESSION array, as with any othervariable. Or as a property of $session.

The former userdata method is deprecated,but you can pass an array containing your new session data to theset() method:

  1. $session->set($array);

Where $array is an associative array containing your new data. Here’san example:

  1. $newdata = [
  2. 'username' => 'johndoe',
  3. 'email' => 'johndoe@some-site.com',
  4. 'logged_in' => TRUE
  5. ];
  6.  
  7. $session->set($newdata);

If you want to add session data one value at a time, set() alsosupports this syntax:

  1. $session->set('some_name', 'some_value');

If you want to verify that a session value exists, simply check withisset():

  1. // returns FALSE if the 'some_name' item doesn't exist or is NULL,
  2. // TRUE otherwise:
  3. isset($_SESSION['some_name'])

Or you can call has():

  1. $session->has('some_name');

Pushing new value to session data

The push method is used to push a new value onto a session value that is an array.For instance, if the ‘hobbies’ key contains an array of hobbies, you can add a new value onto the array like so:

  1. $session->push('hobbies', ['sport'=>'tennis']);

Removing Session Data

Just as with any other variable, unsetting a value in $_SESSION can bedone through unset():

  1. unset($_SESSION['some_name']);
  2.  
  3. // or multiple values:
  4.  
  5. unset(
  6. $_SESSION['some_name'],
  7. $_SESSION['another_name']
  8. );

Also, just as set() can be used to add information to asession, remove() can be used to remove it, by passing thesession key. For example, if you wanted to remove ‘some_name’ from yoursession data array:

  1. $session->remove('some_name');

This method also accepts an array of item keys to unset:

  1. $array_items = ['username', 'email'];
  2. $session->remove($array_items);

Flashdata

CodeIgniter supports “flashdata”, or session data that will only beavailable for the next request, and is then automatically cleared.

This can be very useful, especially for one-time informational, error orstatus messages (for example: “Record 2 deleted”).

It should be noted that flashdata variables are regular session variables,managed inside the CodeIgniter session handler.

To mark an existing item as “flashdata”:

  1. $session->markAsFlashdata('item');

If you want to mark multiple items as flashdata, simply pass the keys as anarray:

  1. $session->markAsFlashdata(['item', 'item2']);

To add flashdata:

  1. $_SESSION['item'] = 'value';
  2. $session->markAsFlashdata('item');

Or alternatively, using the setFlashdata() method:

  1. $session->setFlashdata('item', 'value');

You can also pass an array to setFlashdata(), in the same manner asset().

Reading flashdata variables is the same as reading regular session datathrough $_SESSION:

  1. $_SESSION['item']

Important

The get() method WILL return flashdata items whenretrieving a single item by key. It will not return flashdata whengrabbing all userdata from the session, however.

However, if you want to be sure that you’re reading “flashdata” (and notany other kind), you can also use the getFlashdata() method:

  1. $session->getFlashdata('item');

Or to get an array with all flashdata, simply omit the key parameter:

  1. $session->getFlashdata();

Note

The getFlashdata() method returns NULL if the item cannot befound.

If you find that you need to preserve a flashdata variable through anadditional request, you can do so using the keepFlashdata() method.You can either pass a single item or an array of flashdata items to keep.

  1. $session->keepFlashdata('item');
  2. $session->keepFlashdata(['item1', 'item2', 'item3']);

Tempdata

CodeIgniter also supports “tempdata”, or session data with a specificexpiration time. After the value expires, or the session expires or isdeleted, the value is automatically removed.

Similarly to flashdata, tempdata variables are managed internally by theCodeIgniter session handler.

To mark an existing item as “tempdata”, simply pass its key and expiry time(in seconds!) to the mark_as_temp() method:

  1. // 'item' will be erased after 300 seconds
  2. $session->markAsTempdata('item', 300);

You can mark multiple items as tempdata in two ways, depending on whetheryou want them all to have the same expiry time or not:

  1. // Both 'item' and 'item2' will expire after 300 seconds
  2. $session->markAsTempdata(['item', 'item2'], 300);
  3.  
  4. // 'item' will be erased after 300 seconds, while 'item2'
  5. // will do so after only 240 seconds
  6. $session->markAsTempdata([
  7. 'item' => 300,
  8. 'item2' => 240
  9. ]);

To add tempdata:

  1. $_SESSION['item'] = 'value';
  2. $session->markAsTempdata('item', 300); // Expire in 5 minutes

Or alternatively, using the setTempdata() method:

  1. $session->setTempdata('item', 'value', 300);

You can also pass an array to set_tempdata():

  1. $tempdata = ['newuser' => TRUE, 'message' => 'Thanks for joining!'];
  2. $session->setTempdata($tempdata, NULL, $expire);

Note

If the expiration is omitted or set to 0, the defaulttime-to-live value of 300 seconds (or 5 minutes) will be used.

To read a tempdata variable, again you can just access it through the$_SESSION superglobal array:

  1. $_SESSION['item']

Important

The get() method WILL return tempdata items whenretrieving a single item by key. It will not return tempdata whengrabbing all userdata from the session, however.

Or if you want to be sure that you’re reading “tempdata” (and not anyother kind), you can also use the getTempdata() method:

  1. $session->getTempdata('item');

And of course, if you want to retrieve all existing tempdata:

  1. $session->getTempdata();

Note

The getTempdata() method returns NULL if the item cannot befound.

If you need to remove a tempdata value before it expires, you can directlyunset it from the $_SESSION array:

  1. unset($_SESSION['item']);

However, this won’t remove the marker that makes this specific item to betempdata (it will be invalidated on the next HTTP request), so if youintend to reuse that same key in the same request, you’d want to useremoveTempdata():

  1. $session->removeTempdata('item');

Destroying a Session

To clear the current session (for example, during a logout), you maysimply use either PHP’s session_destroy()function, or the library’s destroy() method. Both will work in exactly thesame way:

  1. session_destroy();
  2.  
  3. // or
  4.  
  5. $session->destroy();

Note

This must be the last session-related operation that you doduring the same request. All session data (including flashdata andtempdata) will be destroyed permanently and functions will beunusable during the same request after you destroy the session.

You may also use the stop() method to completely kill the sessionby removing the old session_id, destroying all data, and destroyingthe cookie that contained the session id:

  1. $session->stop();

Accessing session metadata

In previous CodeIgniter versions, the session data array included 4 itemsby default: ‘session_id’, ‘ip_address’, ‘user_agent’, ‘last_activity’.

This was due to the specifics of how sessions worked, but is now no longernecessary with our new implementation. However, it may happen that yourapplication relied on these values, so here are alternative methods ofaccessing them:

  • session_id: session_id()
  • ip_address: $_SERVER['REMOTE_ADDR']
  • user_agent: $_SERVER['HTTP_USER_AGENT'] (unused by sessions)
  • last_activity: Depends on the storage, no straightforward way. Sorry!

Session Preferences

CodeIgniter will usually make everything work out of the box. However,Sessions are a very sensitive component of any application, so somecareful configuration must be done. Please take your time to considerall of the options and their effects.

You’ll find the following Session related preferences in yourapp/Config/App.php file:

PreferenceDefaultOptionsDescription
sessionDriverCodeIgniterSessionHandlersFileHandlerCodeIgniterSessionHandlersFileHandlerCodeIgniterSessionHandlersDatabaseHandlerCodeIgniterSessionHandlersMemcachedHandlerCodeIgniterSessionHandlersRedisHandlerCodeIgniterSessionHandlersArrayHandlerThe session storage driver to use.
sessionCookieNamecisession[A-Za-z-] characters onlyThe name used for the session cookie.
sessionExpiration7200 (2 hours)Time in seconds (integer)The number of seconds you would like the session to last.If you would like a non-expiring session (until browser is closed) set the value to zero: 0
sessionSavePathNULLNoneSpecifies the storage location, depends on the driver being used.
sessionMatchIPFALSETRUE/FALSE (boolean)Whether to validate the user’s IP address when reading the session cookie.Note that some ISPs dynamically changes the IP, so if you want a non-expiring session youwill likely set this to FALSE.
sessionTimeToUpdate300Time in seconds (integer)This option controls how often the session class will regenerate itself and create a newsession ID. Setting it to 0 will disable session ID regeneration.
sessionRegenerateDestroyFALSETRUE/FALSE (boolean)Whether to destroy session data associated with the old session ID when auto-regeneratingthe session ID. When set to FALSE, the data will be later deleted by the garbage collector.

Note

As a last resort, the Session library will try to fetch PHP’ssession related INI settings, as well as legacy CI settings such as‘sess_expire_on_close’ when any of the above is not configured.However, you should never rely on this behavior as it can causeunexpected results or be changed in the future. Please configureeverything properly.

In addition to the values above, the cookie and native drivers apply thefollowing configuration values shared by the IncomingRequest andSecurity classes:

PreferenceDefaultDescription
cookieDomain‘’The domain for which the session is applicable
cookiePath/The path to which the session is applicable
cookieSecureFALSEWhether to create the session cookie only on encrypted (HTTPS) connections

Note

The ‘cookieHTTPOnly’ setting doesn’t have an effect on sessions.Instead the HttpOnly parameter is always enabled, for securityreasons. Additionally, the ‘cookiePrefix’ setting is completelyignored.

Session Drivers

As already mentioned, the Session library comes with 4 handlers, or storageengines, that you can use:

  • CodeIgniterSessionHandlersFileHandler
  • CodeIgniterSessionHandlersDatabaseHandler
  • CodeIgniterSessionHandlersMemcachedHandler
  • CodeIgniterSessionHandlersRedisHandler
  • CodeIgniterSessionHandlersArrayHandler

By default, the FileHandler Driver will be used when a session is initialized,because it is the safest choice and is expected to work everywhere(virtually every environment has a file system).

However, any other driver may be selected via the public $sessionDriverline in your app/Config/App.php file, if you chose to do so.Have it in mind though, every driver has different caveats, so be sure toget yourself familiar with them (below) before you make that choice.

Note

The ArrayHandler is used during testing and stores all data withina PHP array, while preventing the data from being persisted.

FileHandler Driver (the default)

The ‘FileHandler’ driver uses your file system for storing session data.

It can safely be said that it works exactly like PHP’s own default sessionimplementation, but in case this is an important detail for you, have itmind that it is in fact not the same code and it has some limitations(and advantages).

To be more specific, it doesn’t support PHP’s directory level and modeformats used in session.save_path,and it has most of the options hard-coded for safety. Instead, onlyabsolute paths are supported for public $sessionSavePath.

Another important thing that you should know, is to make sure that youdon’t use a publicly-readable or shared directory for storing your sessionfiles. Make sure that only you have access to see the contents of yourchosen sessionSavePath directory. Otherwise, anybody who can do that, canalso steal any of the current sessions (also known as “session fixation”attack).

On UNIX-like operating systems, this is usually achieved by setting the0700 mode permissions on that directory via the chmod command, whichallows only the directory’s owner to perform read and write operations onit. But be careful because the system user running the script is usuallynot your own, but something like ‘www-data’ instead, so only setting thosepermissions will probably break your application.

Instead, you should do something like this, depending on your environment

  1. mkdir /<path to your application directory>/Writable/sessions/
  2. chmod 0700 /<path to your application directory>/Writable/sessions/
  3. chown www-data /<path to your application directory>/Writable/sessions/

Bonus Tip

Some of you will probably opt to choose another session driver becausefile storage is usually slower. This is only half true.

A very basic test will probably trick you into believing that an SQLdatabase is faster, but in 99% of the cases, this is only true while youonly have a few current sessions. As the sessions count and server loadsincrease - which is the time when it matters - the file system willconsistently outperform almost all relational database setups.

In addition, if performance is your only concern, you may want to lookinto using tmpfs,(warning: external resource), which can make your sessions blazing fast.

DatabaseHandler Driver

The ‘DatabaseHandler’ driver uses a relational database such as MySQL orPostgreSQL to store sessions. This is a popular choice among many users,because it allows the developer easy access to the session data withinan application - it is just another table in your database.

However, there are some conditions that must be met:

  • You can NOT use a persistent connection.
  • You can NOT use a connection with the cacheOn setting enabled.

In order to use the ‘DatabaseHandler’ session driver, you must also create thistable that we already mentioned and then set it as your$sessionSavePath value.For example, if you would like to use ‘ci_sessions’ as your table name,you would do this:

  1. public $sessionDriver = 'CodeIgniter\Session\Handlers\DatabaseHandler';
  2. public $sessionSavePath = 'ci_sessions';

And then of course, create the database table …

For MySQL:

  1. CREATE TABLE IF NOT EXISTS `ci_sessions` (
  2. `id` varchar(128) NOT NULL,
  3. `ip_address` varchar(45) NOT NULL,
  4. `timestamp` int(10) unsigned DEFAULT 0 NOT NULL,
  5. `data` blob NOT NULL,
  6. KEY `ci_sessions_timestamp` (`timestamp`)
  7. );

For PostgreSQL:

  1. CREATE TABLE "ci_sessions" (
  2. "id" varchar(128) NOT NULL,
  3. "ip_address" varchar(45) NOT NULL,
  4. "timestamp" bigint DEFAULT 0 NOT NULL,
  5. "data" text DEFAULT '' NOT NULL
  6. );
  7.  
  8. CREATE INDEX "ci_sessions_timestamp" ON "ci_sessions" ("timestamp");

You will also need to add a PRIMARY KEY depending on your ‘sessionMatchIP’setting. The examples below work both on MySQL and PostgreSQL:

  1. // When sessionMatchIP = TRUE
  2. ALTER TABLE ci_sessions ADD PRIMARY KEY (id, ip_address);
  3.  
  4. // When sessionMatchIP = FALSE
  5. ALTER TABLE ci_sessions ADD PRIMARY KEY (id);
  6.  
  7. // To drop a previously created primary key (use when changing the setting)
  8. ALTER TABLE ci_sessions DROP PRIMARY KEY;

You can choose the Database group to use by adding a new line to theapplicationConfigApp.php file with the name of the group to use:

  1. public $sessionDBGroup = 'groupName';

If you’d rather not do all of this by hand, you can use the session:migration commandfrom the cli to generate a migration file for you:

  1. > php spark session:migration
  2. > php spark migrate

This command will take the sessionSavePath and sessionMatchIP settings into accountwhen it generates the code.

Important

Only MySQL and PostgreSQL databases are officiallysupported, due to lack of advisory locking mechanisms on otherplatforms. Using sessions without locks can cause all sorts ofproblems, especially with heavy usage of AJAX, and we will notsupport such cases. Use session_write_close() after you’vedone processing session data if you’re having performanceissues.

RedisHandler Driver

Note

Since Redis doesn’t have a locking mechanism exposed, locks forthis driver are emulated by a separate value that is kept for upto 300 seconds.

Redis is a storage engine typically used for caching and popular becauseof its high performance, which is also probably your reason to use the‘RedisHandler’ session driver.

The downside is that it is not as ubiquitous as relational databases andrequires the phpredis PHPextension to be installed on your system, and that one doesn’t comebundled with PHP.Chances are, you’re only be using the RedisHandler driver only if you’re alreadyboth familiar with Redis and using it for other purposes.

Just as with the ‘FileHandler’ and ‘DatabaseHandler’ drivers, you must also configurethe storage location for your sessions via the$sessionSavePath setting.The format here is a bit different and complicated at the same time. It isbest explained by the phpredis extension’s README file, so we’ll simplylink you to it:

Warning

CodeIgniter’s Session library does NOT use the actual ‘redis’session.save_handler. Take note only of the path format inthe link above.

For the most common case however, a simple host:port pair should besufficient:

  1. public $sessionDiver = 'CodeIgniter\Session\Handlers\RedisHandler';
  2. public $sessionSavePath = 'tcp://localhost:6379';

MemcachedHandler Driver

Note

Since Memcached doesn’t have a locking mechanism exposed, locksfor this driver are emulated by a separate value that is kept forup to 300 seconds.

The ‘MemcachedHandler’ driver is very similar to the ‘RedisHandler’ one in all of itsproperties, except perhaps for availability, because PHP’s Memcached extension is distributed via PECL and someLinux distributions make it available as an easy to install package.

Other than that, and without any intentional bias towards Redis, there’snot much different to be said about Memcached - it is also a popularproduct that is usually used for caching and famed for its speed.

However, it is worth noting that the only guarantee given by Memcachedis that setting value X to expire after Y seconds will result in it beingdeleted after Y seconds have passed (but not necessarily that it won’texpire earlier than that time). This happens very rarely, but should beconsidered as it may result in loss of sessions.

The $sessionSavePath format is fairly straightforward here,being just a host:port pair:

  1. public $sessionDriver = 'CodeIgniter\Session\Handlers\MemcachedHandler';
  2. public $sessionSavePath = 'localhost:11211';

Bonus Tip

Multi-server configuration with an optional weight parameter as thethird colon-separated (:weight) value is also supported, but we haveto note that we haven’t tested if that is reliable.

If you want to experiment with this feature (on your own risk), simplyseparate the multiple server paths with commas:

  1. // localhost will be given higher priority (5) here,
  2. // compared to 192.0.2.1 with a weight of 1.
  3. public $sessionSavePath = 'localhost:11211:5,192.0.2.1:11211:1';