PHP Luminova: Store PHP Sessions in a Database
Persist PHP session data in a database table with optional encryption and query caching.
Luminova's Session Database Handler stores PHP session data in your configured database. Register it with Session Handling before starting the session. Create the storage table before enabling the handler. Applications sharing the same session table must use compatible session settings and the same encryption configuration when encryption is enabled.
Class Definition
- Full namespace:
Luminova\Sessions\Handlers\SessionDatabaseHandler - This class extends Luminova\Base\AbstractSessionHandler.
- This class inherits PHP's
SessionHandlerInterfaceandSessionIdInterfacefrom its parent. - This class is an ordinary class.
Store and retrieve session values
Use the same handler and table on every request. The first request can save a preference, and the next request carrying the same session cookie can read it.
use Luminova\Sessions\Handlers\SessionDatabaseHandler;
use Luminova\Sessions\Session;
$session = new Session();
$session->setHandler(new SessionDatabaseHandler('sessions'));
if (!$session->start()) {
throw new RuntimeException('Could not start the session.');
}
$theme = $session->get('theme', 'light');
$session->set('theme', 'dark');
$session->close();To enable encrypted storage for an application with encryption configured, pass ['encryption' => true] as the handler options. Add 'cacheable' => true when session queries should use the application's database query cache. To run an initialization check, supply onCreate as a callback accepting the PHP save path and session name and returning a boolean.
Create the session table
Run the following SQL on MySQL or MariaDB before using new SessionDatabaseHandler('sessions').
CREATE TABLE IF NOT EXISTS sessions (
id VARCHAR(255) CHARACTER SET ascii COLLATE ascii_bin NOT NULL,
data MEDIUMTEXT NOT NULL,
ip VARBINARY(32) DEFAULT NULL,
timestamp INT UNSIGNED NOT NULL,
lifetime INT UNSIGNED NOT NULL,
PRIMARY KEY (id),
KEY timestamp_index (timestamp)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;timestamp records activity time, and lifetime stores the configured PHP session lifetime in seconds. If you set columnPrefix to 'session_', prefix all five column names in the table. The table name itself stays sessions.
Use a database migration
Put the same MySQL or MariaDB definition in a migration. Applying or rolling back a migration can run its down() hook, so use this example for a new session table. Dropping an existing session table removes its stored sessions.
// app/Database/Migrations/SessionsMigration.php
namespace App\Database\Migrations;
use Luminova\Database\Migration;
use Luminova\Database\Query\Builder;
use Luminova\Runtime;
class SessionsMigration extends Migration
{
public function up(): bool
{
$sql = <<<'SQL'
CREATE TABLE IF NOT EXISTS sessions (
id VARCHAR(255) CHARACTER SET ascii COLLATE ascii_bin NOT NULL,
data MEDIUMTEXT NOT NULL,
ip VARBINARY(32) DEFAULT NULL,
timestamp INT UNSIGNED NOT NULL,
lifetime INT UNSIGNED NOT NULL,
PRIMARY KEY (id),
KEY timestamp_index (timestamp)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4
SQL;
if (Runtime::get(Runtime::QUERY_DEBUG) === true) {
echo $sql . PHP_EOL;
return true;
}
Runtime::set(Runtime::MIGRATION_SUCCESS, false);
Builder::exec($sql);
$created = Builder::tableExists('sessions');
Runtime::set(Runtime::MIGRATION_SUCCESS, $created);
return $created;
}
public function down(): bool
{
Builder::exec('DROP TABLE IF EXISTS sessions');
$dropped = !Builder::tableExists('sessions');
Runtime::set(Runtime::MIGRATION_SUCCESS, $dropped);
return $dropped;
}
public function alter(): bool
{
return true;
}
}php novakit db:migrate --class=SessionsMigrationMethods
__construct
Use a database table for PHP session storage. Supply handler options when the table uses prefixed columns or the application needs encryption, caching, or lifecycle callbacks.
public function __construct(private string $table, array $options = [])Parameters:
| Parameter | Type | Description |
|---|---|---|
$table | string | Application-defined database table for session records. |
$options | array<string,mixed> | Database storage preferences and shared handler options (default: []). |
Throws:
- Luminova\Exceptions\RuntimeException If the session ID character encoding is unsupported.
Examples:
use Luminova\Sessions\Handlers\SessionDatabaseHandler;
$handler = new SessionDatabaseHandler('sessions', [
'columnPrefix' => 'session_',
'onCreate' => static function (string $path, string $name): bool {
return $name !== '';
},
]);