<?php |
class RedisSessionHandler implements SessionHandlerInterface{ |
private $redis ; |
private $config ; |
private $namespace ; |
private $session_id = null; |
private $maxlifetime = null; |
|
public function __construct( $namespace , $host , $port ) { |
//初始化redis |
$this ->config = array ( |
'host' => $host , |
'port' => $port |
); |
$this ->redis = new Redis(); |
$this ->redis->connect( $this ->config[ 'host' ], $this ->config[ 'port' ]); |
//設(shè)置當(dāng)前的sessionid生成的命名空間 |
$this -> namespace = $namespace ; |
//設(shè)置初始化的session_id |
$session_name = ini_get ( "session.name" ); |
//沒有設(shè)置過session,新的會(huì)話,需要重新生成sessionid |
if ( empty ( $_COOKIE [ $session_name ]) ) { |
$this ->session_id = true; |
} |
} |
public function open( $savePath , $sessionName ){ |
$connect = $this ->redis->connect( $this ->config[ 'host' ], $this ->config[ 'port' ]); |
if (! $connect ) return false; |
//在初次設(shè)置的時(shí)候,重設(shè)PHP本身的session_id并判斷session_id是否已經(jīng)存在 |
$id = session_id(); |
if ( $this ->session_id && $this ->session_id != $id ){ |
do { |
$this ->session_id = $this ->session_id(); |
} while ( $this ->redis->exists( $this -> namespace . '@' . $this ->session_id)); |
session_id( $this ->session_id); |
} |
//設(shè)置生成周期 |
$this ->maxlifetime = ini_get ( "session.gc_maxlifetime" ); |
return true; |
} |
public function close(){ |
$this ->redis->close(); |
return true; |
} |
public function read( $id ){ |
return $this ->redis->get( $this -> namespace . '@' . $id ); |
} |
public function write( $id , $data ){ |
return $this ->redis->setex( $this -> namespace . '@' . $id , $this ->maxlifetime, $data ); |
} |
public function destroy( $id ){ |
$this ->redis-> delete ( $this -> namespace . '@' . $id ); |
return true; |
} |
public function gc( $maxlifetime ){ |
return true; |
} |
/** |
* 生成guid |
*/ |
private function session_id(){ |
$uid = uniqid( "" , true); |
$data = $this -> namespace ; |
$data .= $_SERVER [ 'REQUEST_TIME' ]; |
$data .= $_SERVER [ 'HTTP_USER_AGENT' ]; |
$data .= $_SERVER [ 'SERVER_ADDR' ]; |
$data .= $_SERVER [ 'SERVER_PORT' ]; |
$data .= $_SERVER [ 'REMOTE_ADDR' ]; |
$data .= $_SERVER [ 'REMOTE_PORT' ]; |
$hash = strtoupper (hash( 'ripemd128' , $uid . md5( $data ))); |
return substr ( $hash ,0,32); |
} |
} |
$param = array ( |
"namespace" => '' , |
"redis_host" => '127.0.0.1' , |
"redis_port" => '6379' |
); |
if ( $param ){ |
$handler = new RedisSessionHandler( $param [ 'namespace' ], $param [ 'redis_host' ], $param [ 'redis_port' ]); |
session_set_save_handler( $handler , true); |
}
聯(lián)系客服