欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

PHP实现Session入库/存入redis的方法

程序员文章站 2024-03-12 21:03:02
对于大访问量的站点使用默认的session 并不合适,我们可以将其存入数据库、或者使用redis key-value数据存储方案 首先新建一个session表...

对于大访问量的站点使用默认的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 =''){
     
    $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 ='$id'";
    $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 ='$id'";
    $result = $this->db->getone($sql);
    //var_dump($result);
    if($data==''||isset($data)){
      $data = $this->sessdata;
    }
      if($result){
      //如果存在则更新
  $sql ="update sessions set updatetime = '$newexp',data ='$data' where sid = '$id'";
        //echo $sql;
          $update_data =$this->db->execute($sql);
          if($update_data){
            return true;
          }
         
      }else{
      //不存在则生成生成
  $sql = "insert into sessions(sid,updatetime,data) values('$id','$now','$data')";
    $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 - 'updatetime'>${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('session.use_trans_sid',0);
    ini_set('session.use_cookies',1);
    ini_set('session.cookie_path','/');
      ini_set('session.save_handler','user');
      session_module_name('user');
      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['qq']="qq";
echo $_session['qq'];

数据库代码 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('mysql:host=localhost;dbname=session', 'root','');
  }
 
    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);

使用redis 存储session

<?php
class sessionmanager{
  private $redis;
  private $sessionsavepath;
  private $sessionname;
  private $sessionexpiretime = 30;
  public function __construct(){
    $this->redis = new redis();
    $this->redis->connect('127.0.0.1',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['name'] = "qq";
echo $_session['name'];

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。