要求>=php5.4
sessions表
session_id
session_data
session_expires
xxx
xxx
xxx
//CustomSession.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','123456');
mysqli_set_charset($this->link,'utf8');
mysqli_select_db($this->link,'test1');
if($this->link){
return true;
}
return false;
}
public function close(){
mysqli_close($this->link);
return true;
}
public function read($session_id){
$id = mysql_escape_string($this->link,$session_id);
$sql = "select * from sessions where session_id='{$session_id}' and session_expires>".time();
$result = mysql_query($this->link,$sql);
if(mysqli_num_rows($result) == 1){
return mysql_fetch_assoc($result)['session_data'];
}
//如果有数据返回序列化后的字符串,如果没数据库返回空字符串
return '';
}
public function write($session_id,$session_data){
$newExp = time() + $this->lifetime;
$session_id = mysql_escape_string($this->link,$session_id);
$sql = "select * from sessions where session_id='{$session_id}'";
$result = mysql_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')";
}
mysql_query($this->link,$sql);
return mysql_affected_rows($this->link) == 1;
}
public function destroy($session_id){
$session_id = mysql_escape_string($this->link,$session_id);
$sql = "delete from sessions where session_id='{$session_id}'";
mysqli_query($this->link,$sql);
return mysql_affected_rows($this->link) == 1;
}
public function gc($maxlifetime){
$sql = "delete from sessions where session_expires
mysqli_query($this->link,$sql);
if( mysql_affected_rows($this->link) > 0){
return true;
}else{
return false;
}
}
}
//test.php
require_once 'CustomSession.php';
$CustomSession = new CustomSession;
ini_set('session.save_handler','user');
//php5.4中 需要注册shutdown函数,但是如果使用session_set_save_handler()的OOP原型
//仅需设置“register shutdown”为 true即可
session_set_save_handler($CustomSession,true);
session_start();
$_SESSION['username'] = 'zhangsan';
$_SESSION['age'] = 18;
//dump.php
require_once 'CustomSession.php';
$CustomSession = new CustomSession;
ini_set('session.save_handler','user');
session_set_save_handler($CustomSession,true);
session_start();
print_r($_SESSION);
//删除session
session_destroy();