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封装的数据库保存session功能类就介绍到这了。有一次,我还想给你的红袖子增加香味,和你闲聊新单词,和你一起醉卧在花房里,陪你完成世界上最美丽的依赖。带着执着,轻看痴痴的束缚不要相信,永恒是有尽头的。那时,当我年轻的时候,我被眼前美丽的风景迷住了,不愿意接受现实的励志语录知乎残酷。没关系,你的笑容是蘸了蜂蜜的毒药。我无处可逃。更多相关PHP封装的数据库保存session功能类内容请查看相关栏目,小编编辑不易,再次感谢大家的支持!

您可能有感兴趣的文章
PHP性能优化案例分享

PHP实现短信验证码的发送次数限制

PHP中的异常处理机制深入讲解

PHP常见七种算法合集代码实例

PHP微信扫描二维码关注公众号后自动登录第三方网站