Create a gist now

Instantly share code, notes, and snippets.

@mgng /1.php
Created Dec 14, 2012

What would you like to do?
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