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

本文介绍了一个使用PHP实现的数据库存储Session的类,该类实现了SessionHandlerInterface接口,包括创建、读取、写入、销毁和垃圾回收等方法。通过这个类,可以将用户的Session数据安全地保存到数据库中,提高系统的可扩展性和安全性。
摘要由CSDN通过智能技术生成

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

PHP用数据库保存session类:

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程序设计有所帮助。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值