php 自定义session
session句柄定义:
class SessionHandler{
private $_driver; //驱动
private $_gcMaxLifeTime=1440; //session生存周期
private $_gcProbability=5; //回收因子,不用每次执行session都执行垃圾回收机制,注意:回收因子越大,命中回收机率越大
public function __construct(){
//ini_set('session.gc_divisor',1);
$this->_driver = new MongoSession(); //数据库driver
session_set_save_handler(
array($this, '_open'),
array($this, '_close'),
array($this, '_read'),
array($this, '_write'),
array($this, '_destroy'),
array($this, '_gc')
);
if(!isset($_COOKIE['PHPSESSID'])){
session_start();
setcookie('PHPSESSID', session_id(), 0, '/' );
}else{
session_start();
}
}
public function _open($savePath,$sessionName){
//此是打开数据连接
//$this->_driver->open($savePath,$sessionName);
return true;
}
public function _close(){
//$this->_driver->close();
//关闭数据库连接
return true;
}
/**
* 读取session
* @param unknown_type $key session_id
*/
public function _read($key){
return $this->_driver->read($key);
}
/**
* 写入session
* @param unknown_type $key session_id
* @param unknown_type $value
*/
public function _write($key,$value){
$this->_driver->write($key,$value,$this->_gcMaxLifeTime);
}
/**
* 销毁session
* @param unknown_type $key //session_id
*/
public function _destroy($key){
$this->_driver->delete($key);
}
/**
* 回收session过期的垃圾数据
*/
public function _gc($gcTime){
//rand() 最大值32767
if((rand() % 100) < $this->_gcProbability){
$this->_driver->gc(time());
}
return true;
}
}
mongodb 驱动类:
class MongoSession{
/**
* 读取session
* @param unknown_type $sessionId
*/
public function read($sessionId){
//不执行判读过期时间
$ret = Db::init('session')->findOne(array('sessionId'=>$sessionId));
return isset($ret['data']) ? $ret['data'] : null;
}
/**
* 写入session
* @param unknown_type $sessionId
* @param unknown_type $data
* @param unknown_type $expire
*/
public function write($sessionId,$data,$expire=0){
//判断是否存在session了
$chk = Db::init('session')->findOne(array('sessionId'=>$sessionId));
if($chk){
//存在更新
Db::init('session')->update(
array('sessionId'=>$sessionId),
array('data'=>$data,'expire'=>time()+$expire)
);
}else{
Db::init('session')->insert(array(
'sessionId'=>$sessionId,
'data'=>$data,
'expire'=>time()+$expire
));
}
}
/**
* 删除session
* @param unknown_type $sessionId
*/
public function delete($sessionId){
$ret = Db::init('session')->delete(array('sessionId'=>$sessionId));
return $ret;
}
/**
* 回收
* @param unknown_type $expire
*/
public function gc($expire){
Db::init('session')->delete(array('expire'=>array('$lt'=>$expire)));
}
}