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

php实现将Session写入数据库_PHP

程序员文章站 2022-06-14 19:58:49
...
使用session_set_save_handler()函数,将Session的内容写入数据库

prepare($sql);
      $stmt->execute(array($PHPSESSID));
      if(!$result = $stmt->fetch(PDO::FETCH_ASSOC)){
        return '';
      }
      if(self::$ip == $result['client_ip']){
        self::destroy($PHPSESSID);
        return '';
      }
      if(($result['update_time']+self::$lifetime)<: self::destroy return public static function write phpsessid from session where self::>prepare($sql);
      $stmt->execute(array($PHPSESSID));
      
      if($result=$stmt->fetch(PDO::FETCH_ASSOC)){        
        if($result['data'] != $data || self::$time > ($result['update_time']+30)){
          $sql = "update session set update_time=?,data=? where PHPSESSID = ?";
          $stmt = self::$handler->prepare($sql);
          $stmt->execute(array($self::$time,$data,$PHPSESSID));
        }
      }else{
        if(!empty($data)){
          try{
            $sql = "insert into session(PHPSESSID,update_time,client_ip,data) values(?,?,?,?)";
          }catch(PDOException $e){
            echo $e->getMessage();
          }
          $sth = self::$handler->prepare($sql);
          $sth->execute(array($PHPSESSID,self::$time,self::$ip,$data));
        }
      }
      return true;
    }
    
    public static function destroy($PHPSESSID){
      $sql = "delete from session where PHPSESSID = ?";
      $stmt = self::$handler->prepare($sql);
      $stmt->execute(array($PHPSESSID));
      return true;
    }
    public static function gc($lifetime){
      $sql = "delete from session where update_timeprepare($sql);
      $stmt->execute(array(self::$time-$lifetime));
      return true;
    }
  }
  //使用PDO连接数据库
  try{
    $pdo = new PDO("mysql:host=localhost;dbname=session","root","hwj193");
  }catch(PDOException $e){
    echo $e->getMessage();
  }
  //传递数据库资源
  Session::start($pdo);

以上所述就是本文的全部内容了,希望大家能够喜欢。