将Session写入数据库,Session写入数据库_PHP教程
程序员文章站
2022-06-03 21:29:08
...
将Session写入数据库,Session写入数据库
使用session_set_save_handler()函数,将Session的内容写入数据库
1 php 2 /* 3 *@author Fahy 4 *@link http://home.cnblogs.com/u/HuangWj 5 *数据库为mysql, 6 *数据库名为session,表名为session, 7 *表中字段包括PHPSESSID,update_time,client_ip,data 8 */ 9 class Session{ 10 private static $handler = null; 11 private static $ip = null; 12 private static $lifetime = null; 13 private static $time = null; 14 15 //配置静态变量 16 private static function init($handler){ 17 self::$handler = $handler; //获取数据库资源 18 self::$ip = !empty($_SERVER["REMOTE_ADDR"])? $_SERVER["REMOTE_ADDR"]:'unkonw'; //获取客户端ip 19 self::$lifetime = ini_get('session.gc_maxlifetime'); //获取session生命周期 20 self::$time = time(); //获取当前时间 21 } 22 //调用session_set_save_handler()函数并开启session 23 static function start($pdo){ 24 self::init($pdo); 25 session_set_save_handler( 26 array(__CLASS__,'open'), 27 array(__CLASS__,'close'), 28 array(__CLASS__,'read'), 29 array(__CLASS__,'write'), 30 array(__CLASS__,'destroy'), 31 array(__CLASS__,'gc') 32 ); 33 session_start(); 34 } 35 36 public static function open($path,$name){ 37 return true; 38 } 39 public static function close(){ 40 return true; 41 } 42 43 //查询数据库中的数据 44 public static function read($PHPSESSID){ 45 $sql = "select PHPSESSID,update_time,client_ip,data from session where PHPSESSID=?"; 46 $stmt = self::$handler->prepare($sql); 47 $stmt->execute(array($PHPSESSID)); 48 if(!$result = $stmt->fetch(PDO::FETCH_ASSOC)){ 49 return ''; 50 } 51 if(self::$ip == $result['client_ip']){ 52 self::destroy($PHPSESSID); 53 return ''; 54 } 55 if(($result['update_time']+self::$lifetime)<:>$time