Luminova Framework

PHP Luminova: Backend Session Storage Handlers

Last updated: 2026-11-28 20:57:12

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:


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 World

This 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


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

NameTypeDescription
encryptionboolEncrypts stored session data when enabled. Defaults to false.
session_ipboolIncludes the client IP in session identification when enabled. Defaults to false.
debuggingboolEnables session debugging. Defaults to false.
cacheableboolEnables caching for the database handler. Defaults to false.
sid_entropy_bitsintConfigures the session ID validation pattern. Defaults to 160.
dir_permissionintFile handler directory permissions. Defaults to 0700 in octal.
columnPrefixstring&#124;nullDatabase handler column prefix. Defaults to null.
autoLockDatabaseboolEnables automatic database locking. Defaults to false.
onValidatecallable&#124;nullOptional session ID validation callback. Defaults to null.
onCreatecallable&#124;nullOptional session open callback. Defaults to null.
onClosecallable&#124;nullOptional session close callback. Defaults to null.

Methods

__construct

Constructor to initialize the session handler.

public function __construct(array $options = [])

Parameters:

ParameterTypeDescription
$optionsarray<string, mixed>Configuration options for session handling.

Throws:


setConfig

Set session configuration object.

public function setConfig(Session $config): void

Parameters:

ParameterTypeDescription
$config\App\Config\SessionThe session configuration object.

open

Opens the session storage mechanism.

abstract public function open(string $path, string $name): bool

Parameters:

ParameterTypeDescription
$pathstringThe save path for session files (unused in this implementation).
$namestringThe 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(): bool

Return:

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(): string

Return:

string - Return new generated unique session ID.


validate_sid

Validates a session ID.

abstract public function validate_sid(string $id): bool

Parameters:

ParameterTypeDescription
$idstringThe 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): bool

Parameters:

ParameterTypeDescription
$idstringThe 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|false

Parameters:

ParameterTypeDescription
$max_lifetimeintThe 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|false

Parameters:

ParameterTypeDescription
$idstringThe 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): bool

Parameters:

ParameterTypeDescription
$idstringThe session ID.
$datastringThe 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): bool

Parameters:

ParameterTypeDescription
$idstringThe session ID.
$datastringThe 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): string

Parameters:

ParameterTypeDescription
$bitsintThe 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:


destroySessionCookie

Destroy the session cookie. This method ensures that the cookie session name is destroyed.

protected function destroySessionCookie(): bool

Return:

bool - Return true on success, false on failure.


log

Log error messages for debugging purposes.

protected function log(string $level, string $message): void

Parameters:

ParameterTypeDescription
$levelstringThe log level to use.
$messagestringThe 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' => true

debugging

Determines whether to log error messages during session operations, useful for troubleshooting.

Type: (bool)Default: falseExample:

'debugging' => true

sid_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' => 130

dir_permission

Defines the permissions for the session storage directory, applicable only when using the filesystem handler.

Type: (int)Default: 0777Example:

'dir_permission' => 0700

session_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' => true

columnPrefix

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' => true

onValidate

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;
}