<?php class CustomSession implements SessionHandlerInterface{ private $link; private $lifetime; public function open($savePath,$session_name){ $this->lifetime=get_cfg_var(‘session.gc_maxlifetime‘); $this->link=mysqli_connect(‘localhost‘,‘root‘,‘root‘,‘session_test‘); mysqli_query($this->link,"SET names UTF8"); if($this->link){ return true; } return false; } public function close(){ mysqli_close($this->link); return true; } public function read($session_id){ $sql="SELECT *from sessions where session_id=‘{$session_id}‘ and session_expires >".time(); $result=mysqli_query($this->link,$sql); if(mysqli_num_rows($result)){ return mysqli_fetch_array($result)[‘session_data‘]; } return ""; } public function write($session_id,$session_data){ $newExp=time()+$this->lifetime; //首先查询是否存在指定的session_id,如果存在相当于更新数据,否则是第一次,则写入数据 $sql="SELECT * from sessions where session_id={‘$session_id‘}"; $result=mysqli_query($this->link,$sql); if(mysqli_num_rows($result)==1){ $sql="UPDATE sessions set session_expires=‘{$newExp}‘,session_data=‘{$session_data}‘ where session_id=‘{$session_id}‘ "; }else{ $sql="INSERT into sessions values(‘{$session_id}‘,‘$session_data‘,‘{$newExp}‘)"; } mysqli_query($this->link,$sql); return mysqli_affected_rows($this->link)==1; } public function destroy($session_id){ $sql="DELETE from sessions where session_id=‘{$session_id}‘"; mysqli_query($this->link,$sql); return mysqli_affected_rows($this->link)==1; } public function gc($maxlifetime){ $sql="DELETE from sessions where session_expires<".time(); mysqli_query($this->link,$sql); if(mysqli_affected_rows($this->link)>0){ return true; } return false; } }
<?php header("Content-type:text/html;charset=utf-8"); require_once ‘customSession.php‘; $customSession=new CustomSession(); ini_set(‘session.save_handler‘, ‘user‘); session_set_save_handler($customSession,true); session_start(); $_SESSION[‘name‘]=‘admin‘; $_SESSION[‘pwd‘]=‘123456‘;
//销毁会话,从数据库中删除 <?php require_once ‘customSession.php‘; $customSession=new CustomSession(); ini_set(‘session.save_handler‘, ‘user‘); session_set_save_handler($customSession,true); session_start(); session_destroy();