PHP自定义文件类型的Session处理驱动

自定义SESSION处理驱动可以让我们更灵活的管理SESSION,并更好的服务我们网站业务。

知识: 让自定义类 FileHandle 实现 SessionHandlerInterface 接口

Session处理文件:session.php
class FileHandle implements SessionHandlerInterface
{
    //session 文件保存目录
    protected string $savePath;
    //session 文件过期时间
    protected int $maxLifeTime;
    //构造函数
    public function __construct(string $save_path = 'sessionPath', int $max_life_time = 10)
    {
        $this->savePath = $this->mkdir($save_path);
        echo $this->savePath."<hr/>";
        $this->maxLifeTime = $max_life_time;
    }
    //关闭
    public function close():bool
    {
        return true;
    }
    //销毁
    public function destroy($session_id):bool
    {
        $file = $this->savePath . '/' . $session_id;
        if (file_exists($file)) {
            @unlink($file);
        }
        return true;
    }
    //垃圾回收(该方法实现貌似没有起到作用!目前还在跟着课程学习,以后技术好了再来实现相应功能)
    public function gc($maxlifetime):int
    {
        foreach (glob($this->savePath . '/*') as $file) {
            if (filetime($file) + $this->maxLifeTime < time() && file_exists($file)) {
                @unlink($file);
            }
        }
        return true;
    }
    //创建目录
    protected function mkdir($path):string
    {
        is_dir($path) or mkdir($path, 0755, true);
        return realpath($path);
    }
    //开启
    public function open($save_path, $name):bool
    {
        return true;
    }
    //读取会话数据
    public function read($session_id):string
    {
        return (string)@file_get_contents($this->savePath . '/' . $session_id);
    }
    //写入会话
    public function write($session_id, $session_data):bool
    {
        return file_put_contents($this->savePath . '/' . $session_id, $session_data) === false ? false : true;
    }

}
调用处理程序
include 'session.php';
//声明会话引擎
session_set_save_handler(new FileHandle('sessionPath',10));
session_start();
$_SESSION['ankium'] = "www.ankium.com";
print_r($_SESSION);
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值