自定义Session的文件存储实现
本帖最后由 Sian 于 2016-1-26 16:03 编辑<?php
// 自定义文件存储目录(注意php的读写权限)
$session_path = "/tmp/session/";
// 设置session模式为用户模式,也可以在php.ini这个配置文件中修改
session_module_name("user");
// 注册session生命周期的各阶段方法名
session_set_save_handler("open", "close", "read", "write", "destroy", "gc");
/// 实现生命周期的各方法名
// 开启
function open(){
return true;
}
// 关闭
function close(){
return true;
}
// 读
function read($sid){
global $session_path;
$path = $session_path.$sid;
if(file_exists($path)){
return file_get_contents($path);
}else{
return NULL;
}
}
// 写
function write($sid, $data){
global $session_path;
$path = $session_path.$sid;
return file_put_contents($path, $data);
}
// 销毁
function destroy($sid){
global $session_path;
$path = $session_path.$sid;
return unlink($path);
}
// 回收
function gc($maxlifetime){
global $session_path;
$path = $session_path."*";
// 搜索该目录下的所有文件
$files = glob($path);
foreach($files as $file){
// 文件修改时间+最大存活时间 比当前时间早,则说明已过期,删除!
if (filemtime($file) + $maxlifetime < time()) unlink($file);
}
}
session_start();
改写成类的方式实现:
<?php
class SASession{
private static $path;
public static function start($path = "/tmp/session/"){
self::$path = $path;
// 设置session模式为用户模式,也可以在php.ini这个配置文件中修改
session_module_name("user");
// 注册过程
session_set_save_handler(
array(__CLASS__, "open"),
array(__CLASS__, "close"),
array(__CLASS__, "read"),
array(__CLASS__, "write"),
array(__CLASS__, "destroy"),
array(__CLASS__, "gc"));
session_start();
}
// 开启
public static function open(){
return true;
}
// 关闭
public static function close(){
return true;
}
// 读
public static function read($sid){
$path = self::$path.$sid;
if(file_exists($path)){
return file_get_contents($path);
}else{
return NULL;
}
}
// 写
public static function write($sid, $data){
$path = self::$path.$sid;
return file_put_contents($path, $data);
}
// 销毁
public static function destroy($sid){
$path = self::$path.$sid;
return unlink($path);
}
// 回收
public static function gc($maxlifetime){
$path = self::$path."*";
// 搜索该目录下的所有文件
$files = glob($path);
foreach($files as $file){
// 文件修改时间+最大存活时间 比当前时间早,则说明已过期,删除!
if (filemtime($file) + $maxlifetime < time()) unlink($file);
}
}
}
页:
[1]