Session Management
Relevant source files
The following files were used as context for generating this wiki page:
The CodeIgniter Session Library provides a mechanism for maintaining a user's "state" and tracking their activity across multiple HTTP requests. Since HTTP is a stateless protocol, sessions are essential for building applications that require user persistence, such as remembering login status, shopping cart contents, or user preferences between page loads.
The library is designed to be flexible and secure. It offers several storage backends (called "handlers") to store session data, including files, a database, Redis, or Memcached. It also includes security features like automatic session ID regeneration to help prevent session fixation attacks. The session service is automatically initialized with each request and can be accessed throughout the application via a service or a global helper function.
Sources: source/libraries/sessions.rst:11-20
Configuration
Session behavior is primarily controlled through the app/Config/App.php configuration file. You can modify various parameters to suit your application's needs, from the storage driver to cookie settings.
Sources: source/installation/configuration.rst:142-143, source/libraries/sessions.rst:55-57
The following table details the available session configuration options:
| Property | Type | Default Value | Description |
|---|---|---|---|
$sessionDriver | string | CodeIgniter\Session\Handlers\FileHandler | The storage driver to use. Options include FileHandler, DatabaseHandler, MemcachedHandler, RedisHandler, CookieHandler. |
$sessionCookieName | string | ci_session | The name of the cookie used to store the session ID. |
$sessionExpiration | int | 7200 (2 hours) | The number of seconds the session should last. If set to 0, the session expires when the browser is closed. |
$sessionSavePath | string | WRITEPATH . 'session' | The location to store session data, dependent on the driver. For FileHandler, it's a file path. For DatabaseHandler, it's the table name. |
$sessionMatchIP | bool | false | Whether to match the user's IP address when reading the session. Can cause issues for users with dynamic IPs. |
$sessionTimeToUpdate | int | 300 (5 minutes) | How many seconds must pass before the session ID is automatically regenerated. Set to 0 to disable. |
$sessionRegenerateDestroy | bool | false | Whether to destroy the old session data when the session ID is regenerated. |
Sources: source/libraries/sessions.rst:59-105, source/installation/configuration.rst:142-150
Session Usage
Accessing the Session
You can access the session instance in two primary ways:
- Via Services: This is the recommended method within controllers or other classes.
$session = \Config\Services::session(); - Via Helper Function: A global
session()helper is available for convenience, especially in views.$session = session();
This diagram shows the process of obtaining a session instance.
Working with Session Data
The session library provides several methods for managing data. Data can be stored, retrieved, and removed. Additionally, special data types like "flashdata" and "tempdata" are available for specific use cases.
Storing and Retrieving Data
set(mixed $data, string $value = null): Adds data to the session. Can be an array of key/value pairs or a single key and value.get(string $key = null): Retrieves a specific session item by key. If the key is omitted, it returns all session data.has(string $key): Checks if a specific item exists in the session.
// Storing data
$session->set('user_id', 123);
$session->set(['is_logged_in' => true, 'username' => 'JohnDoe']);
// Retrieving data
$userId = $session->get('user_id');
// Checking for data
if ($session->has('is_logged_in')) {
// User is logged in
}
Sources: source/libraries/sessions.rst:125-156
Flashdata
Flashdata is session data that is only available for the next server request and is then automatically deleted. This is useful for one-time informational or status messages, like "Record updated successfully."
setFlashdata(mixed $data, string $value = null): Sets flashdata.getFlashdata(string $key = null): Retrieves flashdata.
Sources: source/libraries/sessions.rst:193-207
Tempdata
Tempdata is session data that is set to expire after a specific time-to-live (TTL) in seconds. Unlike regular session data which expires globally, tempdata has its own timer.
setTempdata(mixed $data, string $value = null, int $ttl = 300): Sets tempdata with a specific TTL.getTempdata(string $key): Retrieves tempdata.
This diagram illustrates the lifecycle of different session data types.
The diagram shows that regular data persists, flashdata is cleared after one request, and tempdata persists until its TTL expires.
Sources: source/libraries/sessions.rst:218-235
Session Drivers
The Session Library can store data in various ways, each handled by a "driver". The choice of driver affects performance and scalability.
| Driver | Storage Location | Description |
|---|---|---|
FileHandler | Server filesystem (WRITEPATH/session) | Default driver. Simple and works on most environments but can be slow on high-traffic sites. |
DatabaseHandler | A relational database table (ci_sessions) | Stores session data in your application's database. Reliable and portable. Requires a specific table schema. |
MemcachedHandler | Memcached server | High-performance, in-memory storage. Volatile data. Requires Memcached server and memcached PECL extension. |
RedisHandler | Redis server | High-performance, in-memory key-value store. Can persist data. Requires Redis server and redis PECL extension. |
CookieHandler | The user's browser cookie | Stores all session data in the client's cookie. Not recommended due to security risks and size limits (4KB). |
Sources: source/libraries/sessions.rst:267-360
Database Handler Setup
To use the DatabaseHandler, you must first create a table in your database. The framework provides the necessary SQL schema.
The required table structure for the ci_sessions table is as follows:
This diagram shows the entity ci_sessions with its columns and primary key.
You must create this table using the appropriate SQL for your database. For example, for MySQL:
CREATE TABLE `ci_sessions` (
`id` VARCHAR(128) NOT NULL,
`ip_address` VARCHAR(45) NOT NULL,
`timestamp` INT(10) UNSIGNED DEFAULT 0 NOT NULL,
`data` BLOB NOT NULL,
PRIMARY KEY (`id`),
KEY `ci_sessions_timestamp` (`timestamp`)
);
After creating the table, set the driver and save path in app/Config/App.php:
public string $sessionDriver = 'CodeIgniter\Session\Handlers\DatabaseHandler';
public string $sessionSavePath = 'ci_sessions';
Sources: source/libraries/sessions.rst:284-315, source/database/query_builder.rst
Session Lifecycle in a Request
The session is an integral part of the request-response cycle. The following sequence diagram illustrates how the session is handled from the moment a request arrives until a response is sent.
This diagram shows the session being read at the start of a request, used by the application logic, and written back at the end of the request.
Sources: source/libraries/sessions.rst:11-20, source/incoming/incomingrequest.rst:27-30