-
Notifications
You must be signed in to change notification settings - Fork 0
MongoDB Adapter
InitPHP\Sessions\Adapters\MongoDBAdapter stores each session as a single
document in a MongoDB collection.
Requirements: ext-mongodb.
Each document looks like:
{ "_id": "<session id>", "data": "<payload>", "timestamp": 1716998400 }timestamp (Unix time) is refreshed on every write and used by garbage
collection.
| Option | Type | Default | Notes |
|---|---|---|---|
dsn |
string | — | Required. MongoDB connection string. |
collection |
string | — |
Required. Namespace as database.collection. |
The legacy option key
collationis still accepted as an alias forcollection, for backward compatibility with older configs.
Missing dsn/collection throws a
SessionInvalidArgumentException; a failed connection throws a
SessionAdapterException; a missing ext-mongodb throws a
SessionNotSupportedAdapter.
use InitPHP\Sessions\Session;
use InitPHP\Sessions\Adapters\MongoDBAdapter;
$adapter = new MongoDBAdapter([
'dsn' => 'mongodb://127.0.0.1:27017',
'collection' => 'app.sessions', // "database.collection"
]);
Session::createImmutable($adapter)->start();gc() deletes documents whose timestamp is older than gc_maxlifetime and
returns the number removed. It runs on PHP's normal GC schedule, or manually:
$deleted = $adapter->gc(3600);For automatic expiry without relying on PHP's GC, you can additionally create a
MongoDB TTL index on a date
field — but note this adapter stores timestamp as an integer, so a TTL index
would require storing a UTCDateTime instead. The built-in gc() is the
supported path.
-
write()upserts by_id, so repeated writes to the same session update the existing document instead of inserting duplicates. -
read()returns the document'sdata, or''for an unknown session. -
destroy()deletes the single matching document.
- Adapters overview
- PDO Adapter — the SQL equivalent.
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