-
Notifications
You must be signed in to change notification settings - Fork 0
Redis Adapter
InitPHP\Sessions\Adapters\RedisAdapter stores sessions in Redis with a per-key
TTL, so expiry is handled by Redis itself.
Requirements: ext-redis.
| Option | Type | Default | Notes |
|---|---|---|---|
redis |
\Redis |
— | Reuse an existing client. When set, the connection options below are ignored. |
host |
string | 127.0.0.1 |
|
port |
int | 6379 |
|
timeout |
float | 0 |
Connect timeout in seconds. |
password |
string|null | null |
AUTH password. |
database |
int | 0 |
Database index to SELECT. |
ttl |
int | 86400 |
Key expiry in seconds. 0 disables expiry. |
prefix |
string | '' |
Key prefix. |
use InitPHP\Sessions\Session;
use InitPHP\Sessions\Adapters\RedisAdapter;
$adapter = new RedisAdapter([
'host' => '127.0.0.1',
'port' => 6379,
'timeout' => 0,
'password' => null,
'database' => 0,
'ttl' => 86400,
'prefix' => 'sess_',
]);
Session::createImmutable($adapter)->start();If your app already has a configured \Redis, hand it over and skip the
connection options:
$redis = new \Redis();
$redis->connect('127.0.0.1', 6379);
$redis->auth('secret');
$adapter = new RedisAdapter([
'redis' => $redis,
'ttl' => 86400,
'prefix' => 'sess_',
]);
Session::createImmutable($adapter)->start();Each write() stores the payload with SETEX using ttl (when ttl > 0), so
keys expire automatically — no garbage collection needed. Set ttl => 0 to store
keys without expiry (you then manage cleanup yourself).
The session's effective lifetime is the larger of this ttl and whatever your
session cookie lifetime is; align them to avoid surprises.
- No
ext-redis→SessionNotSupportedAdapter. - Connection,
AUTH, orSELECTfailure →SessionAdapterException(a subtype ofSessionException).
use InitPHP\Sessions\Exceptions\SessionAdapterException;
try {
$adapter = new RedisAdapter(['host' => '10.0.0.9', 'port' => 6379]);
} catch (SessionAdapterException $e) {
// Redis is unreachable — fall back or fail fast.
}This adapter supersedes the standalone initphp/redis-session-handler package.
See the Migration Guide.
- Adapters overview
- Memcache / Memcached Adapter — the other in-memory option.
initphp/sessions · MIT License · part of the InitPHP family
Source · Issues · Discussions · Packagist · Contributing · Security Policy
Getting Started
Core Usage
Adapters
- Adapters Overview
- File Adapter
- Redis Adapter
- PDO Adapter
- Cookie Adapter
- Memcache / Memcached Adapter
- MongoDB Adapter
- Custom Adapters
Reference
Practical Guides
Migration & Help