Thinkphp3.2 修改session存储驱动

本文详细介绍了如何在ThinkPHP框架中配置Redis作为Session存储的步骤,包括修改配置文件、自定义Session管理函数及创建SessionRedis类。通过具体代码示例,展示了如何实现Session的读写、过期管理和会话ID的生成。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Setp 1
项目config.php

'SESSION_TYPE'          => 'Redis',   //session存在redis中

Setp 2
\ThinkPHP\Common\functions.php

// session管理函数
function session($name,$value='') 
// 检查驱动类
            if(require_cache(EXTEND_PATH.'Driver/Session/'.$class.'.class.php')) {

Setp 3

\ThinkPHP\Extend\Driver\Session\新增SessionRedis.class.php

<?php

class SessionRedis{
    protected static $savePathPrefix = 'REDISSESSION:';

    protected static $_savePath = '';

    protected static $_instance = null;

    protected static $_redis = null;

    public function __construct(){
        $this::$_redis = ##配置连接redis 
        $this::getSavePath($this->create_id());
    }

    public function create_id(){
        $session_id = $this->detectID();
        if(is_null($session_id)){
            $session_id = uniqid(dechex(mt_rand())) . '__' . date('Y-m-d', time());
            $session_id = authcode($session_id, 'ENCODE');
            $this->id($session_id);
        }
        return $session_id;
    }

    public static function getInstance(){
        if(is_null(self::$_instance)){
            self::$_instance = new SessionRedis();
        }
        return self::$_instance;
    }

    public function open($savePath, $sessionName){
        return true;
    }

    public function close(){
        return $this::$_redis->close();
    }

    /**
     * redis控制过期时间, 因此这里只需返回true即可
     * @param $maxlifetime
     * @return bool
     */
    public function gc($maxlifetime){
        return true;
    }

    public function read($id){
        $eixsts = $this::$_redis->hExists($this::$_savePath, $id);
        if($eixsts){
            return $this::$_redis->hGet($this::$_savePath, $id);
        }
        return "";
    }

    public function write($id, $data){
//        G('run');
        $result = $this::$_redis->hSet($this::$_savePath, $id, $data);
        //设置过期时间
        $expire = $this::$_redis->ttl($this::$_savePath);
        if($expire < 0){
            $this::$_redis->expire($this::$_savePath, ini_get('session.gc_maxlifetime'));
        }
//        echo G('run','end').'s';die;
        return $result?true:false;
    }

    public function destroy($id){
        $eixsts = self::$_redis->hExists($this::$_savePath, $id);
        if($eixsts){
            $this::$_redis->hDel($this::$_savePath, $id);
        }
        return true;
    }

    protected function detectID(){
        $session_id = session_id();
        //当前用户没有session且没有使用旧版session
        if($session_id != ''){
            return session_id();
        }
        if($this->useCookies()){
            if(isset($_COOKIE[session_name()]) && preg_match('/\w+__\d{4}-\d{2}-\d{2}/i', authcode($_COOKIE[session_name()], 'DECODE'))){
                return $_COOKIE[session_name()];
            }
        }else{
            if(isset($_GET[session_name()])){
                return $_GET[session_name()];
            }
            if(isset($_POST[session_name()])){
                return $_POST[session_name()];
            }
        }
        return null;
    }

    protected function useCookies($useCookies = null){
        $return = ini_get('session.use_cookies')?true:false;
        if(isset($useCookies)){
            ini_set('session.use_cookies', $useCookies?1:0);
        }
        return $return;
    }

    protected function id($id = null){
        return isset($id)?session_id($id):session_id();
    }

    protected static function getSavePath($session_id){
        $session_id = authcode($session_id, 'DECODE');
        $sessionIdArr = explode('__', $session_id);
        if(!$sessionIdArr[1]){
            error_log('session_id not found', 0);
        }
        self::$_savePath = self::$savePathPrefix . $sessionIdArr[1];
    }

    public function execute(){
        session_set_save_handler(array(&$this, "open"),
            array(&$this, "close"),
            array(&$this, "read"),
            array(&$this, "write"),
            array(&$this, "destroy"),
            array(&$this, "gc"));
    }
}

Setp 4
配置链接redis 扩展类

class RedisConnect{
private $redis=null;
    private function __construct(){
        $this->redis = new Redis();
            $this->redis->connect('host','port');
            $this->redis->auth('passwd'); //设置密码
            $this->redis->select(1);

    }
    public static function getInstance($index=false){
        if(!(self::$_instance instanceof Redis)){
            self::$_instance = new self($index);
        }
        return self::$_instance->redis;
    }
 }
 
 //连接redis服务器
function RedisConnect(){
    import('@.ORG.RedisConnect');
    return RedisConnect::getInstance($index);
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值