加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

Session保存到数据库的php类分享

发布时间:2020-12-13 06:00:45 所属栏目:PHP教程 来源:网络整理
导读:div class="codetitle" a style="CURSOR: pointer" data="9525" class="copybut" id="copybut9525" onclick="doCopy('code9525')" 代码如下: div class="codebody" id="code9525" ?php class SessionToDB { private $_path = null; private $_name = null; p

<div class="codetitle"><a style="CURSOR: pointer" data="9525" class="copybut" id="copybut9525" onclick="doCopy('code9525')"> 代码如下:<div class="codebody" id="code9525">
<?php
class SessionToDB
{
private $_path = null;
private $_name = null;
private $_pdo = null;
private $_ip = null;
private $_maxLifeTime = 0; public function __construct(PDO $pdo)
{
session_set_save_handler(
array(&$this,'open'),
array(&$this,'close'),'read'),'write'),'destroy'),'gc')
); $this->_pdo = $pdo;
$this->_ip = !empty($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : null;
$this->_maxLifeTime = ini_get('session.gc_maxlifetime');
} public function open($path,$name)
{
return true;
} public function close()
{
return true;
} public function read($id)
{
$sql = 'SELECT FROM session where PHPSESSID = ?';
$stmt = $this->_pdo->prepare($sql);
$stmt->execute(array($id)); if (!$result = $stmt->fetch(PDO::FETCH_ASSOC)) {
return null;
} elseif ($this->_ip != $result['client_ip']) {
return null;
} elseif ($result['update_time']+$this->_maxLifeTime < time()){
$this->destroy($id);
return null;
} else {
return $result['data'];
}
} public function write($id,$data)
{
$sql = 'SELECT
FROM session where PHPSESSID = ?';
$stmt = $this->_pdo->prepare($sql);
$stmt->execute(array($id)); if ($result = $stmt->fetch(PDO::FETCH_ASSOC)) {
if ($result['data'] != $data) {
$sql = 'UPDATE session SET update_time =?,date = ? WHERE PHPSESSID = ?'; $stmt = $this->_pdo->prepare($sql);
$stmt->execute(array(time(),$data,$id));
}
} else {
if (!empty($data)) {
$sql = 'INSERT INTO session (PHPSESSID,update_time,client_ip,data) VALUES (?,?,?)';
$stmt = $this->_pdo->prepare($sql);
$stmt->execute(array($id,time(),$this->_ip,$data));
}
} return true;
} public function destroy($id)
{
$sql = 'DELETE FROM session WHERE PHPSESSID = ?';
$stmt = $this->_pdo->prepare($sql);
$stmt->execute(array($id)); return true;
} public function gc($maxLifeTime)
{
$sql = 'DELETE FROM session WHERE update_time < ?';
$stmt = $this->_pdo->prepare($sql);
$stmt->execute(array(time() - $maxLifeTime)); return true;
}
} try{
$pdo = new PDO('mysql:host=localhost;dbname=rphp4zf','root','rickyfeng');
$pdo->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION); new SessionToDB($pdo);
} catch(PDOException $e) {
echo 'Error: '.$e->getMessage();
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读