MongoDB session driver for CodeIgniter 3
A high-performance session driver that stores CodeIgniter 3 sessions in MongoDB, with locking and expiry handled by MongoDB itself.
- Language
- PHP
- Framework
- CodeIgniter 3.1.5 or higher
- Database
- MongoDB
- Requires
- PECL mongodb extension
Overview
This driver lets CodeIgniter keep its sessions in a MongoDB collection instead of files or a SQL table. You keep using $this->session as usual, and the driver does the rest.
- Concurrency. Session locking is handled by MongoDB's WiredTiger storage engine, so PHP does not need to lock sessions itself.
- Expiry. A MongoDB TTL index removes expired sessions, so PHP's garbage collector has nothing to do.
Compatibility
- CodeIgniter 3.1.5 or higher.
- MongoDB with the PECL mongodb extension installed and enabled in
php.ini. - It is a single file copied into your application. It is not published on Packagist, so there is no
composer require.
Installation
- Download the repository.
- Put
Session_mongo_driver.phpinapplication/libraries/Session/drivers/. Create the folders if they do not exist; the names are case sensitive. - In
application/config/config.php, set the driver:$config['sess_driver'] = 'mongo'; - In the same file, set the connection string as
connection|database|collection:$config['sess_save_path'] = 'mongodb://session_user:secret@localhost:27017/my_app|my_app|sessions'; - Create a TTL index on the collection. This example expires sessions after one hour:
db.sessions.createIndex({ "timestamp": 1 }, { expireAfterSeconds: 3600 })
Usage
Nothing changes in your code. Use CodeIgniter's normal session API:
$this->session->set_userdata('user_id', 42);
$id = $this->session->userdata('user_id');