ThinkPHP5 將session保存到 mysql

參考

我只是個搬運(yùn)工, 一個探路者, 這個不是我寫的, 原作者在這里

為什么有這樣的需求? ...鬼知道為什么不存memcache或者redis,鬼知道你會遇到什么樣的需求, 那還能怎么辦,自己解決唄,為了避免下次再一頓百度..一頓谷歌...我就記錄一下

建立對應(yīng)的數(shù)據(jù)表

CREATE TABLE think_session (
    session_id varchar(255) NOT NULL,
    session_expire int(11) UNSIGNED NOT NULL,
    session_data blob,
    UNIQUE KEY `session_id` (`session_id`)
);

建立數(shù)據(jù)庫驅(qū)動擴(kuò)展類 /extend/driver/session/Mysql.php

默認(rèn)沒有這些目錄和文件, 手動創(chuàng)建吧...

<?php

namespace driver\session;

use SessionHandler;
use think\Db;
use think\Config;
use think\Exception;

/**
 * Class Mysql
 * session 數(shù)據(jù)庫驅(qū)動
 * @package driver\session
 */
class Mysql extends SessionHandler
{
    protected $handler = null;
    protected $table_name = null;
    protected $config = [
        'session_expire' => 3600,           // Session有效期 單位:秒
        'session_prefix' => 'think_',       // Session前綴
        'table_name'     => 'session',      // 表名(不包含表前綴)
    ];
    protected $database = [
        'type'     => 'mysql',        // 數(shù)據(jù)庫類型
        'hostname' => '127.0.0.1',    // 服務(wù)器地址
        'database' => 'my_test',       // 數(shù)據(jù)庫名
        'username' => 'root',         // 用戶名
        'password' => '',             // 密碼
        'hostport' => '3306',         // 端口
        'prefix'   => '',             // 表前綴
        'charset'  => 'utf8',         // 數(shù)據(jù)庫編碼
        'debug'    => true,           // 數(shù)據(jù)庫調(diào)試模式
    ];

    /**
     * Mysql constructor.
     * @param array $config
     * @throws Exception
     */
    public function __construct($config = [])
    {
        // 獲取數(shù)據(jù)庫配置
        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 {
            // 使用默認(rèn)的數(shù)據(jù)庫配置
            $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)
    {
        // 判斷數(shù)據(jù)庫配置是否可用
        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;
    }

    /**
     * 關(guān)閉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_prefix'] . $session_id,
            'session_expire' => time()
        ];
        $sql = 'SELECT session_data FROM ' . $this->table_name . ' WHERE session_id = :session_id AND session_expire > :session_expire';
        $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_prefix'] . $session_id,
            'session_expire' => $this->config['session_expire'] + time(),
            'session_data'   => $session_data
        ];
        $sql = 'REPLACE INTO ' . $this->table_name . ' (session_id, session_expire, session_data) VALUES (:session_id, :session_expire, :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_prefix'] . $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)
    {
        $sql = 'DELETE FROM ' . $this->table_name . ' WHERE session_expire < :session_expire';
        return $this->handler->execute($sql, ['session_expire' => time()]);
    }

}

配置

'session'   => [
    'type'           => 'driver\session\Mysql',
    'auto_start'     => true,
    'session_expire' => 3600,
    'session_prefix' => 'think_',
    'table_name'     => 'think_session',
    'database'       => [
        'hostname' => '127.0.0.1',
        'database' => 'fa.com',
        'username' => 'root',
        'password' => '',
        'hostport' => '3306',
        'prefix'   => '',
        'charset'  => 'utf8',
    ]
],
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容