首頁 >後端開發 >php教程 >PHPSession入庫/存入redis的方法詳解

PHPSession入庫/存入redis的方法詳解

墨辰丷
墨辰丷原創
2018-05-23 09:36:261713瀏覽

這篇文章主要介紹了PHP實現Session入庫/存入redis的方法,小編覺得挺不錯的,現在分享給大家,也給大家做個參考。一起跟著小編過來看看吧

對於大訪問量的網站使用預設的Session 並不合適,我們可以將其存入資料庫、或使用Redis KEY-VALUE資料儲存方案

先新建一個session表

CREATE TABLE `sessions` (
 `sid` char(40) NOT NULL,
 `updatetime` int(20) NOT NULL,
 `data` varchar(200) NOT NULL,
 UNIQUE KEY `sid` (`sid`) USING HASH
) ENGINE=MEMORY DEFAULT CHARSET=utf8;

Mysql 的memory引擎採用記憶體表,所有資料都儲存在內存,操作速度快

#
<?php
//引入数据库文件
include "db.php";
class MySessionHandler implements SessionHandlerInterface
{
  private $savePath;
  private $sessData;
  public $expiretime;  //设置过期时间
  public $db;  //数据库
  public function __construct($hanlder =&#39;&#39;){
     
    $this->db = Database::getInstance();  
     
    //获取数据库实力 
    ///var_dump($this->db);
     
  }
   
  public function open($savePath, $sessionName)
  {
 
    return true;
  }
 
  public function close()
  {
    return true;
  }
 
  public function read($id)
  {  
    $sql ="select * from sessions where sid =&#39;$id&#39;";
    $result = $this->db->execute($sql);
      if(!empty($result)){
         return $this->sessData = $result;
      }
  }
      //函数的参数 $id -> 当前会话ID
      //数据DATA -> 序列化之后的字符串
  public function write($id, $data)
  {
    // echo $id;
    // echo $data;
    $now = time();
    $newExp = $now+$this->expiretime;  //总时间=当前时间 + 期限时间
    $sql = "select * from sessions where sid =&#39;$id&#39;";
    $result = $this->db->getOne($sql);
    //var_dump($result);
    if($data==&#39;&#39;||isset($data)){
      $data = $this->sessData;
    }
      if($result){
      //如果存在则更新
  $sql ="update sessions set updatetime = &#39;$newExp&#39;,data =&#39;$data&#39; where sid = &#39;$id&#39;";
        //echo $sql;
          $update_data =$this->db->execute($sql);
          if($update_data){
            return true;
          }
         
      }else{
      //不存在则生成生成
  $sql = "insert into sessions(sid,updatetime,data) values(&#39;$id&#39;,&#39;$now&#39;,&#39;$data&#39;)";
    $insert_data = $this->db->execute($sql);
    if($insert_data){
    return true;
        }
      }
      return false;
  }
 
  public function destroy($id)
  {    //销毁
    $sql = "delete from sessions where sid="."$id";
    $destory = $this->db->execute($sql);
    if($destory){
       return true;
    }else{
      return false;
    }
  }
 
  public function gc($sessMaxLifeTime)
  {
   $t = time();
  $sql ="delete from sessions where $t - &#39;updatetime&#39;>${sessMaxLifeTime}";
    $data = $this->db->execute($this->tosql);
    if($data){
      return true;
    }else{
      return false;
      }
    return true;
  }
}

實例化

此處PHP 手冊可以有兩種方法

    1,實作了SessionHandlerInterface藉口的物件,自PHP5.4可以使用

    2 ,直接使用  session_set_save_handler

//判断PHP版本
 if(version_compare(PHP_VERSION,5.4)==1){
       
   session_set_save_handler($handler, true);
  session_start();
  }else{  
    ini_set(&#39;session.use_trans_sid&#39;,0);
    ini_set(&#39;session.use_cookies&#39;,1);
    ini_set(&#39;session.cookie_path&#39;,&#39;/&#39;);
      ini_set(&#39;session.save_handler&#39;,&#39;user&#39;);
      session_module_name(&#39;user&#39;);
      session_set_save_handler(array($session,"open"),array($session,"close"),array($session,"read"),array($session,"write"),array($session,"destory"),array($session,"gc"));
      session_start();   
     }
$_SESSION[&#39;QQ&#39;]="QQ";
echo $_SESSION[&#39;QQ&#39;];

資料庫程式碼db.php

<?php 
class Database{
     static $instance;
    static $db;
  static function getInstance(){   
    if(self::$instance){
      return self::$instance;
    }else{
      return new Database();  
    }
  }
  public function __construct(){
    self::$db = new PDO(&#39;mysql:host=localhost;dbname=session&#39;, &#39;root&#39;,&#39;&#39;);
  }
 
    public function getOne($sql){
      $rs =self::$db->query($sql);
      @$rs->setFetchMode(PDO::FETCH_ASSOC);//返回关联数组
      $result = $rs -> fetch();
      return $result;
    }
    public function execute($sql){
       
       
        $rs = self::$db->exec($sql);
        return $rs;
         
    } 
   
 
}
 
 
//$data = Database::getInstance();
//var_dump($data);

資料庫程式碼db.php

使用REDIS 儲存SESSION

<?php
class SessionManager{
  private $redis;
  private $sessionSavePath;
  private $sessionName;
  private $sessionExpireTime = 30;
  public function __construct(){
    $this->redis = new Redis();
    $this->redis->connect(&#39;127.0.0.1&#39;,6379);  //连接redis
    $retval = session_set_save_handler(
      array($this,"open"),
      array($this,"close"),
      array($this,"read"),
      array($this,"write"),
      array($this,"destory"),
      array($this,"gc")
    );
      session_start();
  }
   
    public function open($path,$name){
      return true;
    }
    public function close(){
      return true;
    }
    public function read($id){
      $value = $this->redis->get($id);
      if($value){
        return $value;
      }else{
        return "";
      }
    }
    public function write($id,$data){
      if($this->redis->set($id,$data)){
        $this->redis->expire($id,$this->sessionExpireTime); 
         //设置过期时间
        return true;
      }
      return false;
    }
    public function destory($id){
      if($this->redis->delete($id)){
        return true;
      }
      return false;
    }
    public function gc($maxlifetime){
      return true;
    }
    //析构函数
    public function __destruct(){
      session_write_close();
    }
     
}
 
 
$re = new SessionManager();
$_SESSION[&#39;name&#39;] = "qq";
echo $_SESSION[&#39;name&#39;];

#相關推薦:

##php學習筆記之物件導向

php反射類別ReflectionClass用法分析_php技巧

#PHP

程式設計入門的基本語法知識點總結_php基礎

#############

以上是PHPSession入庫/存入redis的方法詳解的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn