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

PHP封装的数据库保存session功能类

程序员文章站 2024-04-02 16:02:34
本文实例讲述了php封装的数据库保存session功能类。分享给大家供大家参考,具体如下: php用数据库保存session类:

本文实例讲述了php封装的数据库保存session功能类。分享给大家供大家参考,具体如下:

php用数据库保存session类:

<?php
class safesessionhandler implements sessionhandlerinterface {
  public $save_path;
  public $session_name;
  public $table;
  public function __construct() {
    $this->table = new table("safe_session");
  }
  private function session_id_parse($session_id) {
    $time = hexdec(substr($session_id, 0, 8));
    $skey = substr($session_id, 8);
    return array($time, $skey);
  }
  public function close() {
    loginfo("close: ");
    return true;
  }
  public function create_sid() {
    loginfo("create_sid: ");
    $time = time();
    $skey = "";
    $char = "0123456789abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz";
    for ($i=0; $i<52; $i++) {
      $skey .= $char{mt_rand(0, 61)};
    }
    $session = array(
      "time" => $time,
      "skey" => $skey,
      "sval" => "",
    );
    $this->table->insert($session);
    return dechex($time) . $skey;
  }
  public function destroy($session_id) {
    loginfo("destroy: %s", $session_id);
    list($time, $skey) = $this->session_id_parse($session_id);
    $this->table->where("time = ?", $time)->where("skey = ?", $skey)->delete();
    return true;
  }
  public function gc($maxlifetime) {
    loginfo("gc: %s", $maxlifetime);
    $this->table->where("time < ?", time() - 86400 * 30)->delete();
    return true;
  }
  public function open($save_path, $session_name) {
    loginfo("open: %s, %s", $save_path, $session_name);
    $this->save_path = $save_path;
    $this->session_name = $session_name;
    return true;
  }
  public function read($session_id) {
    loginfo("read: %s", $session_id);
    list($time, $skey) = $this->session_id_parse($session_id);
    $row = $this->table->where("time = ?", $time)->where("skey = ?", $skey)->select()->fetch();
    if (empty($row)) {
      return "";
    }
    return $row["sval"];
  }
  public function write($session_id, $session_data) {
    loginfo("write: %s, %s", $session_id, $session_data);
    $session = array("sval" => $session_data,);
    list($time, $skey) = $this->session_id_parse($session_id);
    $this->table->where("time = ?", $time)->where("skey = ?", $skey)->update($session);
    return true;
  }
}

更多关于php相关内容感兴趣的读者可查看本站专题:《php字符串(string)用法总结》、《php数组(array)操作技巧大全》、《php运算与运算符用法总结》、《php网络编程技巧总结》、《php基本语法入门教程》、《php操作office文档技巧总结(包括word,excel,access,ppt)》、《php日期与时间用法总结》、《php面向对象程序设计入门教程》、《php+mysql数据库操作入门教程》及《php常见数据库操作技巧汇总

希望本文所述对大家php程序设计有所帮助。