错误1:Warning: session_start(): Failed to read session data: user (path: D:\phpstudy_pro\Extensions\tmp\tmp) in D:\phpstudy_pro\WWW\cheshi\0606.php on line 52
要在read方法中return $value; 改成return serialize($value);
也可以这样写 return (string)$value;
第二次访问时,错误SQL语句是insert into sess values ('ntf7qg00e8lp8sqvlbuqgflcge','s:32:"s:26:"s:20:"s:14:"stu|s:3:"stu";',unix_timestamp())
数据库已经存在这个sess_id 主键的时候。要更改SQL插入语句
$sql="insert into sess values ('$sess_id','$sess_value',unix_timestamp()) on duplicate key update sess_value='$sess_value',sess_time=unix_timestamp()";
实现代码:
需要引入mypdo库
class Session{
private $mypdo;
public function __construct(){
session_set_save_handler(
[$this,'open'],
[$this,'close'],
[$this,'read'],
[$this,'write'],
[$this,'destroy'],
[$this,'gc']
);
session_start();
}
function open(){
$this->mypdo=MyPDO::getInstance($GLOBALS['config']['database']);
return true;
}
//关闭会话
function close(){
return true;
}
//读取会话
function read($sess_id){
$sql="select sess_value from sess where sess_id='$sess_id'";
return (string)$this->mypdo->fetchColumn($sql);
}
//写入会话
function write($sess_id,$sess_value){
$sql="insert into sess values ('$sess_id','$sess_value',unix_timestamp()) on duplicate key update sess_value='$sess_value',sess_time=unix_timestamp()";
return $this->mypdo->exec($sql)!==false;
}
//销毁会话
function destroy($sess_id){
$sql="delete from sess where sess_id='$sess_id'";
$this->mypdo->exec($sql);
return $this->mypdo->exec($sql)!==false;
}
//垃圾回收
function gc($lifetime){
$expires=time()-$lifetime;
$sql="delete * from sess where sess_time<$expires";
$this->mypdo->exec($sql);
return $this->mypdo->exec($sql)!==false;
}
}
new Session();
$_SESSION['stu']=['tom','berry','ketty'];
$_SESSION['name']="李白";
echo $_SESSION['name'];
print_r($_SESSION['stu']);
session_destroy();