-
Notifications
You must be signed in to change notification settings - Fork 0
Adapters
An adapter is a session save handler: it tells PHP where session data is
read from and written to. Every bundled adapter extends
AbstractAdapter and implements
InitPHP\Sessions\Interfaces\AdapterInterface, which extends PHP's native
SessionHandlerInterface.
You wire one in by passing it to createImmutable():
use InitPHP\Sessions\Session;
use InitPHP\Sessions\Adapters\RedisAdapter;
Session::createImmutable(new RedisAdapter([
'host' => '127.0.0.1',
'port' => 6379,
]))->start();With no adapter, PHP's configured default handler (usually files) is used.
| Adapter | Best for | Requires | Expiry |
|---|---|---|---|
| File | A custom save path/prefix without touching php.ini
|
— |
gc() by file mtime |
| Redis | Fast, shared sessions across app servers | ext-redis |
per-key TTL |
| PDO | Sessions in your existing SQL database |
ext-pdo + driver |
gc() by timestamp |
| Cookie | Stateless servers; no server storage at all |
initphp/encryption, ext-openssl
|
cookie lifetime |
| Memcache(d) | Fast, ephemeral, in-memory sessions |
ext-memcached/ext-memcache
|
per-item TTL |
| MongoDB | Document-store deployments | ext-mongodb |
gc() by timestamp |
If you write your own adapter, two contract details matter most:
-
read()returns the raw, session-encoded payload that PHP handed towrite()— not your individual$_SESSIONvalues. For a session that does not exist yet, return an empty string''. Returningfalsesignals a genuine read failure; returning a serialized empty array (a:0:{}) corrupts the session. -
write()/destroy()returnbool, andgc()returns the number of deleted sessions (orfalse).
AbstractAdapter gives you safe defaults for open(), close() and gc(), so a
minimal adapter only implements read(), write() and destroy(). See
Custom Adapters.
-
Construction-time problems (missing extension, bad options, unreachable
backend) throw — see Exceptions:
- missing extension/library →
SessionNotSupportedAdapter - missing/invalid option →
SessionInvalidArgumentException - connection/auth failure →
SessionAdapterException
- missing extension/library →
-
Runtime read/write/destroy calls do not throw — they return
false(or''for an absent session), as PHP's session machinery expects.
Two adapters let you inject an already-configured client instead of connection options, so you can share one connection across your app:
// Redis
new RedisAdapter(['redis' => $existingRedisInstance, 'ttl' => 86400]);
// PDO
new PDOAdapter(['pdo' => $existingPdoInstance, 'table' => 'sessions']);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