通過redis實現session共享-php


<?php
class redisSession{
    /**
     * 保存session的數據庫表的信息
     */
    private $_options = array(
        'handler' => null, //數據庫連接句柄
        'host' => null,
        'port' => null,
        'lifeTime' => null,
        'prefix'   => 'PHPREDIS_SESSION:'
    );

    /**
     * 構造函數
     * @param $options 設置信息數組
     */
    public function __construct($options=array()){
        if(!class_exists("redis", false)){
            die("必須安裝redis擴展");
        }
        if(!isset($options['lifeTime']) || $options['lifeTime'] <= 0){
            $options['lifeTime'] = ini_get('session.gc_maxlifetime');
        }
        $this->_options = array_merge($this->_options, $options);
    }

    /**
     * 開始使用該驅動的session
     */
    public function begin(){
        if($this->_options['host'] === null ||
           $this->_options['port'] === null ||
           $this->_options['lifeTime'] === null
        ){
            return false;
        }
        //設置session處理函數
        session_set_save_handler(
            array($this, 'open'),
            array($this, 'close'),
            array($this, 'read'),
            array($this, 'write'),
            array($this, 'destory'),
            array($this, 'gc')
        );
    }
    /**
     * 自動開始回話或者session_start()開始回話后第一個調用的函數
     * 類似於構造函數的作用
     * @param $savePath 默認的保存路徑
     * @param $sessionName 默認的參數名,PHPSESSID
     */
    public function open($savePath, $sessionName){
        if(is_resource($this->_options['handler'])) return true;
        //連接redis
        $redisHandle = new Redis();
        $redisHandle->connect($this->_options['host'], $this->_options['port']);
        if(!$redisHandle){
            return false;
        }

        $this->_options['handler'] = $redisHandle;
//        $this->gc(null);
        return true;

    }

    /**
     * 類似於析構函數,在write之后調用或者session_write_close()函數之后調用
     */
    public function close(){
        return $this->_options['handler']->close();
    }

    /**
     * 讀取session信息
     * @param $sessionId 通過該Id唯一確定對應的session數據
     * @return session信息/空串
     */
    public function read($sessionId){
        $sessionId = $this->_options['prefix'].$sessionId; 
        return $this->_options['handler']->get($sessionId);
    }

    /**
     * 寫入或者修改session數據
     * @param $sessionId 要寫入數據的session對應的id
     * @param $sessionData 要寫入的數據,已經序列化過了
     */
    public function write($sessionId, $sessionData){
        $sessionId = $this->_options['prefix'].$sessionId; 
        return $this->_options['handler']->setex($sessionId, $this->_options['lifeTime'], $sessionData);
    }

    /**
     * 主動銷毀session會話
     * @param $sessionId 要銷毀的會話的唯一id
     */
    public function destory($sessionId){
        $sessionId = $this->_options['prefix'].$sessionId; 
//        $array = $this->print_stack_trace();
//        log::write($array);
        return $this->_options['handler']->delete($sessionId) >= 1 ? true : false;
    }

    /**
     * 清理繪畫中的過期數據
     * @param 有效期
     */
    public function gc($lifeTime){
        //獲取所有sessionid,讓過期的釋放掉
        //$this->_options['handler']->keys("*");
        return true;
    }
    //打印堆棧信息
    public function print_stack_trace()
    {
        $array = debug_backtrace ();
        //截取用戶信息
        $var = $this->read(session_id());
        $s = strpos($var, "index_dk_user|");
        $e = strpos($var, "}authId|");
        $user = substr($var,$s+14,$e-13);
        $user = unserialize($user);
        //print_r($array);//信息很齊全
        unset ( $array [0] );
        if(!empty($user)){
          $traceInfo = $user['id'].'|'.$user['user_name'].'|'.$user['user_phone'].'|'.$user['presona_name'].'++++++++++++++++\n';
        }else{
          $traceInfo = '++++++++++++++++\n';
        }
        $time = date ( "y-m-d H:i:m" );
        foreach ( $array as $t ) {
            $traceInfo .= '[' . $time . '] ' . $t ['file'] . ' (' . $t ['line'] . ') ';
            $traceInfo .= $t ['class'] . $t ['type'] . $t ['function'] . '(';
            $traceInfo .= implode ( ', ', $t ['args'] );
            $traceInfo .= ")\n";
        }
        $traceInfo .= '++++++++++++++++';
        return $traceInfo;
    }

}

入口處調用

$handler = new redisSession(array(
                'host' => "127.0.0.1",
                'port' => "6379"
        ));
$handler->begin();

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM