class session {
private static $pdo;//数据库连接
private static $lifetime;//session的失效时间
private static $date;//当前时间
//php_ini配置session
//session.gc_maxlifetime = 设置多少秒过期(系统默认1440秒=24分钟)
//session.gc_divisor = 设置回收机制,值为当用户刷新多少次执行一次回收(系统默认1000次执行一次回收)
//session.use_cookies = 是否启动客户端cookie来存储sessionId(系统默认1)(1启动,0关闭)
//session.cookie_lifetime = 0浏览器关闭时,sessionId消失,(系统默认0)(单位秒)
//mysql表字段
//sessionId
//finishDate
//data
//updateDate
static function init(){
//数据库连接采用pdo模式
self::$pdo=new PDO("mysql:host=数据库IP;dbname=数据库名称;port=端口号","数据库用户名","数据库密码",array(PDO::ATTR_PERSISTENT=>true));
self::$pdo->exec("set names utf8");
self::$lifetime=2592000;//多少秒过期,设置了30天
self::$date=date('Y-m-d H:i:s');//当前时间
}
static function start(){
self::init();//初始化默认值
session_set_save_handler(
array(__CLASS__,"open"),//打开
array(__CLASS__,"close"),//关闭
array(__CLASS__,"read"),//读
array(__CLASS__,"write"),//写
array(__CLASS__,"destroy"),//删除
array(__CLASS__,"gc")//回收
);
@session_start();//开启session
}
//打开
public static function open($path,$name){
return true;
}
//关闭
public static function close(){
self::$pdo = null;
return true;
}
//读
public static function read($sessionId){
$sql = self::$pdo->prepare('select `finishDate`,`data` from `session` where `sessionId`=?');
$sql->execute(array($sessionId));
if(!$res=$sql->fetch(PDO::FETCH_ASSOC)){
return '';
}
if(self::$date>$res['finishDate']){
self::destroy($sessionId);
return '';
}
return $res['data'];
}
//写
public static function write($sessionId,$data){
if(!empty($data)){
$sql = self::$pdo->prepare('select `sessionId` from `session` where `sessionId`=? and now()<`finishDate`');
$sql->execute(array($sessionId));
if($res = $sql->fetch(PDO::FETCH_ASSOC)){
$update = self::$pdo->prepare('update `session` set `updateDate`=?,`data`=? where `sessionId`=?');
$update->execute(array(self::$date,$data,$sessionId));
}else{
$insert = self::$pdo->prepare('insert into `session`(`sessionId`,`updateDate`,`finishDate`,`data`)values(?,?,?,?)');
$insert->execute(array($sessionId,self::$date,date("Y-m-d H:i:s",strtotime(date("Y-m-d H:i:s")." +".self::$lifetime." second")),$data));
}
}
return true;
}
//删除
public static function destroy($sessionId){
$sql = self::$pdo->prepare('delete from `session` where `sessionId`=?');
$sql->execute(array($sessionId));
return true;
}
//回收
private static function gc($lifetime){
$sql = self::$pdo->prepare('delete from `session` where now()>`finishDate`');
$sql->execute();
return true;
}
}
//调用
session::start();
腾讯专用的session存储到数据库方法,基于PDO
最新推荐文章于 2024-09-23 17:22:35 发布