PHP中用户自定义Session处理机制
*session_start() 会触发open(),read()
session_commit()以及页面执行完毕都会顺序触发 write(),close()*
自定义Session处理机制首先要设置php.ini选项session.save_handler = user,也可在 PHP程序 中进行设置:ini_set(‘session.save_handler’, ‘user’);
注意一定要把 “session.auto_start = 1 改成 session.auto_start = 0 ,不然设置ini_set(‘session.save_handler’, ‘user’);会引起报错。
接下来着重看 session_set_save_handle() 函数,此函数有六个参数:
session_set_save_handler(string open, string close, string read, string write, string destroy, string gc)
各个参数为各项操作的函数名,这些操作依次对应是:打开、关闭、读取、写入、销毁、垃圾回收。
<?php
class FileSessionHandler
{
private $savePath;
//第一个参数$save_path对应的是ini_get("session.save_path")
//第二个参数$name对应的是ini_get("session.name")
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")
);
// the following prevents unexpected effects when using objects as save handlers
register_shutdown_function("session_write_close");
声明:该文观点仅代表作者本人,入门客AI创业平台信息发布平台仅提供信息存储空间服务,如有疑问请联系rumenke@qq.com。