PHP类分享:Session保存到数据库

  作者:bea

下面是Session保存到数据库的PHP类,和大家分享下,欢迎拍砖的哈,拍的时候看着点就行哈! classSessionToDB { private$_path=null; private$_name=null; private$_pdo=null; private$_ip=null; private$_maxLifeTime=0; publicfunction__construct(PDO$pdo) { session_set_save_handler( array(

下面是Session保存到数据库的PHP类,和大家分享下,欢迎拍砖的哈,拍的时候看着点就行哈!

classSessionToDB

{

private$_path=null;

private$_name=null;

private$_pdo=null;

private$_ip=null;

private$_maxLifeTime=0;

publicfunction__construct(PDO$pdo)

{

session_set_save_handler(

array(&$this,'open'),

array(&$this,'close'),

array(&$this,'read'),

array(&$this,'write'),

array(&$this,'destroy'),

array(&$this,'gc')

);

$this->_pdo=$pdo;

$this->_ip=!empty($_SERVER['REMOTE_ADDR'])?$_SERVER['REMOTE_ADDR']:null;

$this->_maxLifeTime=ini_get('session.gc_maxlifetime');

}

publicfunctionopen($path,$name)

{

returntrue;

}

publicfunctionclose()

{

returntrue;

}

publicfunctionread($id)

{

$sql='SELECT*FROMsessionwherePHPSESSID=?';

$stmt=$this->_pdo->prepare($sql);

$stmt->execute(array($id));

if(!$result=$stmt->fetch(PDO::FETCH_ASSOC)){

returnnull;

}elseif($this->_ip!=$result['client_ip']){

returnnull;

}elseif($result['update_time']+$this->_maxLifeTime

$this->destroy($id);

returnnull;

}else{

return$result['data'];

}

}

publicfunctionwrite($id,$data)

{

$sql='SELECT*FROMsessionwherePHPSESSID=?';

$stmt=$this->_pdo->prepare($sql);

$stmt->execute(array($id));

if($result=$stmt->fetch(PDO::FETCH_ASSOC)){

if($result['data']!=$data){

$sql='UPDATEsessionSETupdate_time=?,date=?WHEREPHPSESSID=?';

$stmt=$this->_pdo->prepare($sql);

$stmt->execute(array(time(),$data,$id));

}

}else{

if(!empty($data)){

$sql='INSERTINTOsession(PHPSESSID,update_time,client_ip,data)VALUES(?,?,?,?)';

$stmt=$this->_pdo->prepare($sql);

$stmt->execute(array($id,time(),$this->_ip,$data));

}

}

returntrue;

}

publicfunctiondestroy($id)

{

$sql='DELETEFROMsessionWHEREPHPSESSID=?';

$stmt=$this->_pdo->prepare($sql);

$stmt->execute(array($id));

returntrue;

}

publicfunctiongc($maxLifeTime)

{

$sql='DELETEFROMsessionWHEREupdate_time

$stmt=$this->_pdo->prepare($sql);

$stmt->execute(array(time()-$maxLifeTime));

returntrue;

}

}

try{

$pdo=newPDO('mysql:host=localhost;dbname=rphp4zf','root','rickyfeng');

$pdo->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);

newSessionToDB($pdo);

}catch(PDOException$e){

echo'Error:'.$e->getMessage();

}

有用  |  无用

猜你喜欢