Skip to content

Instantly share code, notes, and snippets.

@tobalsan
Created July 29, 2014 11:30
Show Gist options
  • Save tobalsan/4e23f74dc06400576d46 to your computer and use it in GitHub Desktop.
Save tobalsan/4e23f74dc06400576d46 to your computer and use it in GitHub Desktop.

Store PHP session in Redis

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment