介紹了php實現Session存儲到Redis的方法,php Session可以保存到文本或者內存、還有數據庫,本文講的是存到Redis的方法.
對於大訪問量的站點使用默認的Session 並不合適,我們可以將其存入數據庫、或者使用Redis KEY-VALUE數據存儲方案
首先新建一個session表
CREATE TABLE `sessions` (
`sid` char(40) NOT NULL,
`updatetime` int(20) NOT NULL,
`data` varchar(200) NOT NULL,
UNIQUE KEY `sid` (`sid`) USING HASH
) ENGINE=MEMORY DEFAULT CHARSET=utf8;
Mysql 的memory引擎採用內存表,所有數據存儲在內存,操作速度快
<?php
//引入數據庫文件
include "";
class MySessionHandler implements SessionHandlerInterface
{
private $savePath;
private $sessData;
public $expiretime; //設置過期時間
public $db; //數據庫
public function __construct($hanlder =''){
$this->db = Database::getInstance();
//獲取數據庫實力
///var_dump($this->db);
}
public function open($savePath, $sessionName)
{
return true;
}
public function close()
{
return true;
}
public function read($id)
{
$sql ="select * from sessions where sid ='$id'";
$result = $this->db->execute($sql);
if(!empty($result)){
return $this->sessData = $result;
}
}
//函數的.參數 $id -> 當前會話ID
//數據DATA -> 序列化之後的字符串
public function write($id, $data)
{
// echo $id;
// echo $data;
$now = time();
$newExp = $now+$this->expiretime; //總時間=當前時間 + 期限時間
$sql = "select * from sessions where sid ='$id'";
$result = $this->db->getOne($sql);
//var_dump($result);
if($data==''||isset($data)){
$data = $this->sessData;
}
if($result){
//如果存在則更新
$sql ="update sessions set updatetime = '$newExp',data ='$data' where sid = '$id'";
//echo $sql;
$update_data =$this->db->execute($sql);
if($update_data){
return true;
}
}else{
//不存在則生成生成
$sql = "insert into sessions(sid,updatetime,data) values('$id','$now','$data')";
$insert_data = $this->db->execute($sql);
if($insert_data){
return true;
}
}
return false;
}
public function destroy($id)
{ //銷燬
$sql = "delete from sessions where sid="."$id";
$destory = $this->db->execute($sql);
if($destory){
return true;
}else{
return false;
}
}
public function gc($sessMaxLifeTime)
{
$t = time();
$sql ="delete from sessions where $t - 'updatetime'>${sessMaxLifeTime}";
$data = $this->db->execute($this->tosql);
if($data){