Session 如何';取消设置';会话保存处理程序?
由于某些原因,我必须使用默认的保存处理程序初始化会话 前面的代码使用session\u set\u save\u handler()显式设置自定义处理程序Session 如何';取消设置';会话保存处理程序?,session,php,Session,Php,由于某些原因,我必须使用默认的保存处理程序初始化会话 前面的代码使用session\u set\u save\u handler()显式设置自定义处理程序 在我的情况下,更改以前的代码不是一个现实的选择,所以有人知道如何将处理程序还原为默认值吗?例如是否存在会话\u还原\u保存\u处理程序或会话\u取消设置\u保存\u处理程序函数或等效函数?这里我必须回答自己的问题,因为没有人说任何话: 首先,PHP没有提供session\u restore\u save\u处理程序或session\u uns
在我的情况下,更改以前的代码不是一个现实的选择,所以有人知道如何将处理程序还原为默认值吗?例如是否存在会话\u还原\u保存\u处理程序或会话\u取消设置\u保存\u处理程序函数或等效函数?这里我必须回答自己的问题,因为没有人说任何话: 首先,PHP没有提供
session\u restore\u save\u处理程序
或session\u unset\u save\u处理程序
,而且(到目前为止)没有原生的方式让事情恢复到以前的样子。出于某种原因,PHP团队并没有给我们这样处理会话处理程序的选项
其次,本机会话机制可以用以下代码模拟
class FileSessionHandler
{
private $savePath;
function open($savePath, $sessionName)
{
$this->savePath = $savePath;
if (!is_dir($this->savePath)) {
mkdir($this->savePath, 0777);
}
return true;
}
function close()
{
return true;
}
function read($id)
{
return (string)@file_get_contents("$this->savePath/sess_$id");
}
function write($id, $data)
{
return file_put_contents("$this->savePath/sess_$id", $data) === false ? false : true;
}
function destroy($id)
{
$file = "$this->savePath/sess_$id";
if (file_exists($file)) {
unlink($file);
}
return true;
}
function gc($maxlifetime)
{
foreach (glob("$this->savePath/sess_*") as $file) {
if (filemtime($file) + $maxlifetime < time() && file_exists($file)) {
unlink($file);
}
}
return true;
}
}
$handler = new FileSessionHandler();
session_set_save_handler(
array($handler, 'open'),
array($handler, 'close'),
array($handler, 'read'),
array($handler, 'write'),
array($handler, 'destroy'),
array($handler, 'gc')
);
register_shutdown_function('session_write_close');
类FileSessionHandler
{
私有$savePath;
函数打开($savePath,$sessionName)
{
$this->savePath=$savePath;
如果(!is_dir($this->savePath)){
mkdir($this->savePath,0777);
}
返回true;
}
函数关闭()
{
返回true;
}
函数读取($id)
{
return(string)@file_get_contents(“$this->savePath/sess_$id”);
}
函数写入($id$data)
{
返回文件内容(“$this->savePath/sess_$id”,$data)==false?false:true;
}
函数销毁($id)
{
$file=“$this->savePath/sess_$id”;
如果(文件_存在($file)){
取消链接($文件);
}
返回true;
}
函数gc($maxlifetime)
{
foreach(glob(“$this->savePath/sess_*”)作为$file){
如果(filemtime($file)+$maxlifest
这种逻辑最接近于PHP的本机会话处理逻辑,但在不同的情况下,当然会出现不可预测的行为。我现在可以得出的结论是,基本会话操作已经全部包含在内。从PHP 5.4开始,您可以通过直接实例化SessionHandler类还原为默认会话处理程序:
session_set_save_handler(new SessionHandler(), true);