PHP Luminova: Backend Session Storage Handlers
Implement a custom session storage handler or extend the shared behavior used by Luminova’s session handlers.
The Session Handler Abstract Class is a base for implementing a custom backend session handler. Your subclass implements PHP’s session storage operations, including reading and writing session data. The base class handles shared configuration and provides session ID and cookie helpers. Use the completed handler with the Session Management Class.
See Also:
- Database Session handler - Session handler for managing session in database.
- Filesystem Session Handler - Session handler for managing session in filesystem.
Implementing a Custom Session Handler
To create a custom session handler, extend the AbstractSessionHandler class and implement the necessary abstract methods, including those from SessionHandlerInterface and SessionIdInterface. This allows you to define how session data is stored, retrieved, validated, and destroyed.
// /app/Utils/CustomHandler.php
namespace App\Utils;
use Luminova\Base\AbstractSessionHandler;
abstract class CustomHandler extends AbstractSessionHandler
{
public function __construct(array $options = [])
{
parent::__construct($options);
// Your initialization logic here
}
// Implement Abstract methods for SessionHandlerInterface and SessionIdInterface
}Example Usage
Register a concrete handler before starting the session. This example uses the built-in filesystem handler. A concrete custom handler can be registered in the same way.
use Luminova\Sessions\Session;
use Luminova\Sessions\Handlers\SessionFileHandler;
$session = new Session();
$session->setHandler(new SessionFileHandler(options: [
'encryption' => true, // Enable session data encryption
'session_ip' => true, // Bind session to client IP for security
]));
$session->start();
// Set and retrieve session data
$session->set('foo', 'Hello World');
echo $session->get('foo'); // Outputs: Hello WorldThis setup demonstrates the flexibility of the abstract session handler while ensuring that session management can be easily customized to meet specific application requirements.
Class Definition
- Full namespace:
Luminova\Base\AbstractSessionHandler - This class implements \SessionHandlerInterface, \SessionIdInterface
- This class is abstract.
Properties
config
Session config.
protected ?Session $config = null;fileHash
Hold the last session data hashed-value.This can be used to compare the session data and determine if should update the data or ignore if no changes have been made.
protected string $fileHash = '';pattern
Session ID validation pattern (e.g, [0-9a-z]{20}).
protected string $pattern = '';options
Configuration options for session handling.
/**
* @var array<string, mixed>
*/
protected array $options = [
'encryption' => false,
'session_ip' => false,
'debugging' => false,
'cacheable' => false, // for database handler only
'sid_entropy_bits' => 160,
'dir_permission' => 0700, // for file handler only
'columnPrefix' => null, // for database handler only
'autoLockDatabase' => false, // for database handler only
'onValidate' => null,
'onCreate' => null,
'onClose' => null
];Properties
| Name | Type | Description |
|---|---|---|
encryption | bool | Encrypts stored session data when enabled. Defaults to false. |
session_ip | bool | Includes the client IP in session identification when enabled. Defaults to false. |
debugging | bool | Enables session debugging. Defaults to false. |
cacheable | bool | Enables caching for the database handler. Defaults to false. |
sid_entropy_bits | int | Configures the session ID validation pattern. Defaults to 160. |
dir_permission | int | File handler directory permissions. Defaults to 0700 in octal. |
columnPrefix | string|null | Database handler column prefix. Defaults to null. |
autoLockDatabase | bool | Enables automatic database locking. Defaults to false. |
onValidate | callable|null | Optional session ID validation callback. Defaults to null. |
onCreate | callable|null | Optional session open callback. Defaults to null. |
onClose | callable|null | Optional session close callback. Defaults to null. |
Methods
__construct
Constructor to initialize the session handler.
public function __construct(array $options = [])Parameters:
| Parameter | Type | Description |
|---|---|---|
$options | array<string, mixed> | Configuration options for session handling. |
Throws:
- Luminova\Exceptions\RuntimeException - if an error occurred.
setConfig
Set session configuration object.
public function setConfig(Session $config): voidParameters:
| Parameter | Type | Description |
|---|---|---|
$config | \App\Config\Session | The session configuration object. |
open
Opens the session storage mechanism.
abstract public function open(string $path, string $name): boolParameters:
| Parameter | Type | Description |
|---|---|---|
$path | string | The save path for session files (unused in this implementation). |
$name | string | The session name. |
Return:
bool - Return bool value from callback onCreate, otherwise always returns true for successful initialization.
close
Closes the session storage mechanism.
abstract public function close(): boolReturn:
bool - Return bool value from callback onClose, otherwise always returns true for successful cleanup.
create_sid
Creates a new session unique identifier.
public function create_sid(): stringReturn:
string - Return new generated unique session ID.
validate_sid
Validates a session ID.
abstract public function validate_sid(string $id): boolParameters:
| Parameter | Type | Description |
|---|---|---|
$id | string | The session ID to validate. |
Return:
bool - Return bool value from onValidate callback, otherwise returns true if id is valid and exists else false.
destroy
Deletes a session by ID.
abstract public function destroy(string $id): boolParameters:
| Parameter | Type | Description |
|---|---|---|
$id | string | The session ID. |
Return:
bool - Return true on success, false on failure.
gc
Performs garbage collection for expired sessions.
abstract public function gc(int $max_lifetime): int|falseParameters:
| Parameter | Type | Description |
|---|---|---|
$max_lifetime | int | The maximum session lifetime in seconds. |
Return:
int|false - Return the number of deleted sessions, or false on failure.
read
Reads session data by ID.
abstract public function read(string $id): string|falseParameters:
| Parameter | Type | Description |
|---|---|---|
$id | string | The session ID. |
Return:
string|false - Stored session data, an empty string when no data exists, or false on failure. The built-in filesystem handler returns an empty string when the session is missing or invalid.
write
Writes session data.
abstract public function write(string $id, string $data): boolParameters:
| Parameter | Type | Description |
|---|---|---|
$id | string | The session ID. |
$data | string | The session data. |
Return:
bool - Return true on success, false on failure.
update_timestamp
Updates the session timestamp.
public function update_timestamp(string $id, string $data): boolParameters:
| Parameter | Type | Description |
|---|---|---|
$id | string | The session ID. |
$data | string | The session data. |
Return:
bool - Return true on success, false on failure.
initSessionIDPattern
Initializes the session ID pattern and updates session length settings if required.
This method determines the appropriate session ID length based on the specified number of bits and the session.sid_bits_per_character setting. If the current session.sid_length is insufficient to meet the required entropy, the method updates it dynamically. It also generates a regex pattern that reflects the character set and length of the session ID for validation purposes.
protected static function initSessionIDPattern(int $bits): stringParameters:
| Parameter | Type | Description |
|---|---|---|
$bits | int | The total number of bits to be used for the session ID (e.g., 160, 130). |
Return:
string - Returns the generated regex pattern for the session ID. The pattern ensures compatibility with the character set and length.
Throws:
- Luminova\Exceptions\RuntimeException - If an unsupported value for
session.sid_bits_per_characteris encountered.
destroySessionCookie
Destroy the session cookie. This method ensures that the cookie session name is destroyed.
protected function destroySessionCookie(): boolReturn:
bool - Return true on success, false on failure.
log
Log error messages for debugging purposes.
protected function log(string $level, string $message): voidParameters:
| Parameter | Type | Description |
|---|---|---|
$level | string | The log level to use. |
$message | string | The log error message. |
Configuration Options
This section outlines the available options for configuring a session database handler. These options provide flexibility in managing session data storage and behavior.
encryption
Enables or disables encryption for session data. When set to true, the session data is encrypted before storage and decrypted upon retrieval. The encryption utilizes the default application encryption configuration based on App\Config\Encryption.
Type: (bool)Default: falseExample:
'encryption' => truedebugging
Determines whether to log error messages during session operations, useful for troubleshooting.
Type: (bool)Default: falseExample:
'debugging' => truesid_entropy_bits
Specifies the number of entropy bits used when generating the session ID, impacting the randomness and security of session IDs.
Type: (int)Default: 160Example:
'sid_entropy_bits' => 130dir_permission
Defines the permissions for the session storage directory, applicable only when using the filesystem handler.
Type: (int)Default: 0777Example:
'dir_permission' => 0700session_ip
When enabled, this option ties the session to the IP address of the client, enhancing security by preventing session hijacking from different IPs.
Type: (bool)Default: falseExample:
'session_ip' => truecolumnPrefix
Specifies a prefix to be added to all session-related database columns. This can help avoid column name collisions in shared database tables.
Type: (string|null)Default: nullExample:
'columnPrefix' => 'user_session_'cacheable
Determines whether session data should be cached in memory for faster access. When true, caching mechanisms (if available) are utilized. This is applicable only when using the filesystem handler.
Type: (bool)Default: falseExample:
'cacheable' => trueonValidate
A custom callback function executed during session ID validation. This can be used to perform additional checks, such as validating user-agent strings or custom tokens.
Type: (callable|null)Default: nullExample:
'onValidate' => function (string $id, bool $exists): bool {
// Custom validation logic
return $exists && doExtraCheck($id);
}onCreate
A custom callback function triggered when a new session is created. This is useful for initializing session-specific resources or logging creation events.
Type: (callable|null)Default: nullExample:
'onCreate' => function (string $path, string $name): bool {
// Logic for new session creation
return true;
}onClose
A custom callback function triggered when a session is closed or destroyed. This can be used to clean up resources or log session closure events.
Type: (callable|null)Default: nullExample:
'onClose' => function (): bool {
// Logic for session closure
return true;
}