项目封装session会话类

[复制链接]
查看1195 | 回复0 | 2020-11-25 09:15 | 显示全部楼层 |阅读模式
项目封装session会话类
在Lib目录下创建Session.class.php页面
  1. <?php
  2. namespace Lib;
  3. class Session{
  4.     private $mypdo;
  5.     public function __construct() {
  6.         session_set_save_handler(
  7.             [$this,'open'],
  8.             [$this,'close'],
  9.             [$this,'read'],
  10.             [$this,'write'],
  11.             [$this,'destroy'],
  12.             [$this,'gc']
  13.         );
  14.         session_start();
  15.     }
  16.     public function open() {
  17.         $this->mypdo= \Core\MyPDO::getInstance($GLOBALS['config']['database']);
  18.         return true;
  19.     }
  20.     //关闭会话
  21.     public function close() {
  22.         return true;
  23.     }
  24.     //读取会话
  25.     public function read($sess_id) {
  26.         $sql="select sess_value from sess where sess_id='$sess_id'";
  27.         return (string)$this->mypdo->fetchColumn($sql);
  28.     }
  29.     //写入会话
  30.     public function write($sess_id,$sess_value) {
  31.         $sql="insert into sess values ('$sess_id','$sess_value',unix_timestamp()) on duplicate key update sess_value='$sess_value',sess_time=unix_timestamp()";
  32.         return $this->mypdo->exec($sql)!==false;
  33.     }
  34.     //销毁会话
  35.     public function destroy($sess_id) {
  36.         $sql="delete from sess where sess_id='$sess_id'";
  37.         return $this->mypdo->exec($sql)!==false;
  38.     }
  39.     //垃圾回收
  40.     public function gc($lifetime) {
  41.         $expires=time()-$lifetime;        //过期时间点
  42.         $sql="delete from sess where sess_time<$expires";
  43.         return $this->mypdo->exec($sql)!==false;
  44.     }
  45. }
复制代码


您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

UID
1
贡献
387
丢币
38902
主题
4607
回帖
116
注册时间
2018-9-25
最后登录
2024-4-16