<?php
/**
* redis 替代文件存储Session
*/
#PHP 的session_set_save_handler函数,定义用户级Session保存函数(如打开,关闭,写入等)
#bool session_set_save_handler(callback open, callback close, callback read, callback write, callback destroy, callback gc)
#在使用该函数前,需要把php.ini 配置文件中的 session.save_hadler选项设置为user
#编写Session管理类SessionManager
class SessionManager{
private $redis;
private $sessionSavePath;
private $sessionName;
private $sessionExpireTime = 30;
public function __construct(){
$this->redis = new Redis();
$this->redis->connect("localhost", 6379);
$retval = session_set_save_handler(
array($this, "open"),
array($this, "close"),
array($this, "read"),
array($this, "write"),
array($this, "destroy"),
array($this, "gc")
);
session_start();
}
public function open($path, $name){
return true;
}
public function close(){
return true;
}
public function read($id){
$value = $this->redis->get($id);
if($value){
return $value;
}else{
return '';
}
}
public function write($id, $data){
if($this->redis->set($id, $data)){
$this->redis->expire($id, $this->sessionExpireTime);
return true;
}
return false;
}
public function destroy($id){
if($this->redis->delete($id)){
return true;
}
return false;
}
public function gc($maxlifetime){
return true;
}
public function __destruct(){
session_write_close();
}
}
#使用时包含 SessionManger类,然后实例化一个 SessionManger对象即可