<?php
header('content-type:text/html;charset=utf-8');
class RedisSessionHandler{
public $ttl; //失效时间
protected $db; //操作存储介质对象
/**
* 构造方法;
* 注入操作介质对象,设置失效时间;
*/
public function __construct($db,$time=1440) {
$this->db = $db;
$this->ttl = $time;
}
/**
* 打开方法。
*/
function _open()
{
//
}
/**
* 关闭方法。
* 清空操作存储介质对象。
*/
function _close()
{
$this->db = null;
unset($this->db);
}
/**
* 读取数据方法。
*/
function _read($id)
{
//根据 session_id get方式获取
$sessData = $this->db->get($id);
//重新更新失效时间。
$this -> db -> set( $id , $this->db->get($id), 0 , $this->ttl);
//返回获取信息。
return $sessData;
}
/**
* 写入方法。
*/
function _write($id, $data)
{
//存在即修改,不存在写入
$this -> db -> set( $id ,$data, 0 , $this->ttl);
}
/**
* 删除方法。
*/
function _destroy($id)
{
$this->db->del($id);
}
/**
* 垃圾回收机制。
*/
function _clean($max)
{
//
}
}
//实例化操作 memcache 对象
$mem = new \Memcache();
//链接 memcache 服务器
$mem-> connect('127.0.0.1',11211);
//实例化自定义对象
$sessHandler = new RedisSessionHandler($mem);
//更改 session 存储方式。
session_set_save_handler(
array($sessHandler, '_open'),
array($sessHandler, '_close'),
array($sessHandler, '_read'),
array($sessHandler, '_write'),
array($sessHandler, '_destroy'),
array($sessHandler, '_clean')
);
//操作 session ,验证定义的类有没有错。
session_start();
//$_SESSION['name']='i am superman';
//var_dump(isset($_SESSION["names"]));
echo $_SESSION["name"];
?>
session 存入 memcahce
最新推荐文章于 2022-06-14 11:05:35 发布
本文介绍了一种使用PHP实现自定义Session处理器的方法,并通过集成Redis作为存储介质来增强Session管理的功能。具体包括如何通过构造方法注入操作介质对象并设置失效时间,以及实现Session的基本操作如读取、写入和删除等。
2750

被折叠的 条评论
为什么被折叠?



