This example is based on a use with Silex, but it can be adapted to any other framework or plain PHP.
Fist, create the RedisSessionHandler.php
class file:
<?php
class RedisSessionHandler implements SessionHandlerInterface
{
public $ttl;
protected $db;
protected $prefix;
public function __construct(Predis\Client $db, $prefix = 'PHPSESSID:') {
$this->db = $db;
$this->prefix = $prefix;
$this->ttl = ini_get('session.gc_maxlifetime');
}
public function open($savePath, $sessionName) {
// No action necessary because connection is injected
// in constructor and arguments are not applicable.
}
public function close() {
$this->db = null;
unset($this->db);
}
public function read($id) {
$id = $this->prefix . $id;
$sessData = $this->db->get($id);
$this->db->expire($id, $this->ttl);
return $sessData;
}
public function write($id, $data) {
$id = $this->prefix . $id;
$this->db->setEx($id, $this->ttl, $data);
}
public function destroy($id) {
$this->db->del($this->prefix . $id);
}
public function gc($maxLifetime) {
// no action necessary because using EXPIRE
}
}
?>
Then, in the app.php
file:
<?php
//...
// Redis DB connection
$app['redis'] = new Predis\Client();
// Configure Redis session storage
$app->register(new SessionServiceProvider());
$app['session.storage.handler'] = new RedisSessionHandler($app['redis']);
//...
?>
And you're done ! Now sessions are stored in Redis.