Skip to content

Instantly share code, notes, and snippets.

@mgng
Created December 14, 2012 06:41
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mgng/4283210 to your computer and use it in GitHub Desktop.
Save mgng/4283210 to your computer and use it in GitHub Desktop.
redis + php + session
<?php
$vcap_services = json_decode( getenv( "VCAP_SERVICES" ) );
$credentials = $vcap_services->{"redis-2.2"}[0]->credentials;
$host = $credentials->host;
$port = $credentials->port;
$pass = $credentials->password;
ini_set( 'session.save_handler', 'redis' );
ini_set( 'session.save_path', "tcp://{$host}:{$port}?auth={$pass}" );
session_start();
<?php
require_once 'RedisSessionHandler.php';
$vcap_services = json_decode( getenv( "VCAP_SERVICES" ) );
$credentials = $vcap_services->{"redis-2.2"}[0]->credentials;
$host = $credentials->host;
$port = $credentials->port;
$pass = $credentials->password;
$rsh = new RedisSessionHandler( $host, $port, $pass );
session_set_save_handler(
array( $rsh, 'open' ),
array( $rsh, 'close' ),
array( $rsh, 'read' ),
array( $rsh, 'write' ),
array( $rsh, 'destroy' ),
array( $rsh, 'gc' )
);
register_shutdown_function( 'session_write_close' );
session_start();
<?php
// RedisSessionHandler.php
class RedisSessionHandler
{
const PREFIX = 'REDISSESS:';
const TIMEOUT = 2.0;
const SESS_TIMEOUT = 1200;
public function __construct( $host, $port, $password ) {
$this->_redis = new Redis();
$this->_host = $host;
$this->_port = $port;
$this->_password = $password;
return true;
}
public function open( $savePath, $sessionName ) {
$this->_redis->connect( $this->_host, $this->_port, self::TIMEOUT );
$this->_redis->setOption( Redis::OPT_PREFIX, self::PREFIX );
$this->_redis->auth( $this->_password );
return true;
}
public function close() {
return true;
}
public function read( $id ){
return gzinflate( $this->_redis->get( $id ) );
}
public function write( $id, $data ){
$this->_redis->setex( $id, self::SESS_TIMEOUT, gzdeflate( $data, 9 ) );
return true;
}
public function destroy( $id ){
$this->_redis->delete( $id );
return true;
}
public function gc( $maxlifetime ) {
return true;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment