redis + php + session
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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(); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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(); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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