<返回更多

ThinkPHP 5.0添加mysql存session驱动

2019-10-24    
加入收藏

php中Session默认都是用文件存储的,thinkphp是提供了redis和Memcache的存储类,但是没有提供MySQL的储存类,现在修改为用数据库的方式储存,直接上代码:

<?php
/**
 * session 存mysql类
 * dcr163.cn
 */
namespace thinksessiondriver;
use SessionHandler;
use thinkDb;
use thinkConfig;
use thinkException;
/**
 * 数据库方式Session驱动
 * 表结构
 * CREATE TABLE `tp_session` (
 * `session_id` VARCHAR(150) NOT NULL COMMENT 'session_key',
 * `session_data` TEXT COMMENT 'session_值',
 * `expire_time` int(11) NOT NULL DEFAULT '0' COMMENT '过期时间',
 * KEY `idx_session_id` (`session_id`),
 * UNIQUE KEY `session_id` (`session_id`),
 * KEY `idx_expire_time` (`expire_time`)
 * ) ENGINE=MyISAM DEFAULT CHARSET=utf8mb4 COMMENT='session表';
 *
 */
class Mysql extends SessionHandler
{
 protected $handler = null;
 protected $table_name = null;
 protected $config = [
 'expire_time' => 3600, // Session有效期 单位:秒
 'session_name' => 'tp_', // Session前缀
 'table_name' => 'session', // 表名(不包含表前缀)
 ];
 protected $database = [
 'type' => 'mysql', // 数据库类型
 'hostname' => '127.0.0.1', // 服务器地址
 'database' => '', // 数据库名
 'username' => 'root', // 用户名
 'password' => '', // 密码
 'hostport' => '3306', // 端口
 'prefix' => 'tp_', // 表前缀
 'charset' => 'utf8', // 数据库编码
 'debug' => true, // 数据库调试模式
 ];
 public function __construct($config = [])
 {
 // 获取数据库配置
 if(isset($config['database']) && !empty($config['database']))
 {
 if(is_array($config['database'])){
 $database = $config['database'];
 }elseif(is_string($config['database'])){
 $database = Config::get($config['database']);
 }else{
 throw new Exception('session error:database');
 }
 unset($config['database']);
 }else{
 // 使用默认的数据库配置
 $database = Config::get('database');
 }
 $this->config = array_merge($this->config, $config);
 $this->database = array_merge($this->database, $database);
 }
 /**
 * 打开Session
 * @access public
 * @param string $save_path
 * @param mixed $session_name
 * @return bool
 * @throws Exception
 */
 public function open($save_path, $session_name)
 {
 // 判断数据库配置是否可用
 if(empty($this->database)){
 throw new Exception('session error:database empty');
 }
 $this->handler = Db::connect($this->database);
 $this->table_name = $this->database['prefix'] . $this->config['table_name'];
 return true;
 }
 /**
 * 关闭Session
 * @access public
 */
 public function close()
 {
 $this->gc(ini_get('session.gc_maxlifetime'));
 $this->handler = null;
 return true;
 }
 /**
 * 读取Session
 * @access public
 * @param string $session_id
 * @return bool|string
 */
 public function read($session_id)
 {
 $where = [
 'session_id' => $this->config['session_name'] . $session_id,
 'expire_time' => time()
 ];
 $sql = 'SELECT session_data FROM ' . $this->table_name . ' WHERE session_id = :session_id AND expire_time > :expire_time';
 $result = $this->handler->query($sql, $where);
 if(!empty($result)){
 return $result[0]['session_data'];
 }
 return '';
 }
 /**
 * 写入Session
 * @access public
 * @param string $session_id
 * @param String $session_data
 * @return bool
 */
 public function write($session_id, $session_data)
 {
 $params = [
 'session_id' => $this->config['session_name'] . $session_id,
 'expire_time' => $this->config['expire_time'] + time(),
 'session_data' => $session_data
 ];
 $sql = 'REPLACE INTO ' . $this->table_name . ' (session_id, expire_time, session_data) VALUES (:session_id, :expire_time, :session_data)';
 $result = $this->handler->execute($sql, $params);
 return $result ? true : false;
 }
 /**
 * 删除Session
 * @access public
 * @param string $session_id
 * @return bool|void
 */
 public function destroy($session_id)
 {
 $where = [
 'session_id' => $this->config['session_name'] . $session_id
 ];
 $sql = 'DELETE FROM ' . $this->table_name . ' WHERE session_id = :session_id';
 $result = $this->handler->execute($sql, $where);
 return $result ? true : false;
 }
 /**
 * Session 垃圾回收
 * @access public
 * @param string $sessMaxLifeTime
 * @return bool
 */
 public function gc($sessMaxLifeTime)
 {
 $where = [
 'expire_time' => time()
 ];
 $sql = 'DELETE FROM ' . $this->table_name . ' WHERE expire_time < :expire_time';
 return $this->handler->execute($sql, $where);
 }
}

把上面的文件保存为:Mysql.php

放在目录:/thinkphp/library/think/session/driver 下;

然后在配置文件中修改session的储存方式,文件位置 : /Application/config.php

'session' => [
 'id' => '',
 // SESSION_ID的提交变量,解决flash上传跨域
 'var_session_id' => '',
 // SESSION 前缀
 'prefix' => 'think',
 // 驱动方式 支持redis memcache memcached
 'type' => 'mysql',
 // 是否自动开启 SESSION
 'auto_start' => true,
 // mysql 存session的表名
 'table_name' => 'session',
 // 是否自动开启 SESSION
],

以上就是TP5把session存储到Mysql中的步骤,这时打开页面就可以看到session已经存到mysql表里了

声明:本站部分内容来自互联网,如有版权侵犯或其他问题请与我们联系,我们将立即删除或处理。
▍相关推荐
更多资讯 >>>