慕课学习-->PHP中的会话控制-->第三章 SESSION的使用-->3-5自定义会话管理器
<?php
class CustomSession implements SessionHandlerInterface{
private $links;
private $lifetime;//生存周期
public function open($savePath,$session_name){
$this->lifetime=get_cfg_var('session.gc_maxlifetime');
$this->links=mysqli_connect('localhost','root','***');
mysqli_set_charset($this->links,'utf8');
mysqli_select_db($this->links,'test1');
if($this->links){
return true;
}
return false;
}
public function close(){
mysqli_close($this->links);
return true;
}
public function read($session_id){
$id=mysqli_escape_string($this->links,$session_id);
$sql="select * from sessions where session_id='{$id}' and session_expires>".time();
$result=mysqli_query($this->links,$sql);
if($result && mysqli_num_rows($result)==1){
return mysqli_fetch_assoc($result)['session_data'];
}
return '';
}
public function write($session_id,$session_data){
$newExp=time()+$this->lifetime;
$session_id=mysqli_escape_string($this->links,$session_id);
//首先查询是否存在指定的Session_id,如果存在相当于更新数据,否则是第一次,则写入数据
$sql="select * from sessions where session_id='{$session_id}'";
echo $sql;
$result=mysqli_query($this->links,$sql);
if($result && mysqli_num_rows($result)==1){
$sql2="update sessions set session_expires='{$newExp}',session_data='{$session_data}' where session_id='{$session_id}'";
}else{
$sql2="insert into sessions values('{$session_id}','{$session_data}','{$newExp}')";
}
$re=mysqli_query($this->links,$sql2);
return mysqli_affected_rows($this->links)==1;
}
public function destroy($session_id){
$session_id=mysqli_escape_string($this->links,$session_id);
$sql="delete from sessions where session_id='{$session_id}'";
mysqli_query($this->links,$sql);
return mysqli_affected_rows($this->links)==1;
}
public function gc($maxlifetime){
$sql="delete from sessions where session_expires<".time();
mysqli_query($this->links,$sql);
if(mysqli_affected_rows($this->links)>0){
return true;
}
return false;
}
}
?>
<?php
require_once 'CustomSession.php';
$CustomSession=new CustomSession();
ini_set('session.save_handler','user');
session_set_save_handler($CustomSession,true);
session_start();
$_SESSION['username']='muzi';
$_SESSION['age']=23;
$_SESSION['test']='this is a test3';
$_SESSION['email']='xxxxxxxxx@qq.com';
///打印SESSION
var_dump($_SESSION);
//销毁会话
session_destroy();
?>
--
-- 数据库: `test1`
--
-- --------------------------------------------------------
--
-- 表的结构 `sessions`
--
CREATE TABLE IF NOT EXISTS `sessions` (
`session_id` char(40) NOT NULL,
`session_data` varchar(200) DEFAULT NULL,
`session_expires` int(11) DEFAULT NULL,
PRIMARY KEY (`session_id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;