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

yipeiwu_com6年前PHP代码库
复制代码 代码如下:

<?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'),
array(&$this, 'read'),
array(&$this, 'write'),
array(&$this, 'destroy'),
array(&$this, '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();
}

相关文章

PHP常用工具函数小结【移除XSS攻击、UTF8与GBK编码转换等】

本文实例总结了PHP常用工具函数。分享给大家供大家参考,具体如下: 移除XSS攻击脚本 function RemoveXSS($val) { // remove all no...

隐藏X-Space个人空间下方版权方法隐藏X-Space个人空间标题隐藏X-Space个人空间管理版权方法

版权可以在css中设置隐藏. 由于文件被ZEND所以不能删除,也不建议删除. 1.隐藏X-Space个人空间下方版权方法 修改/css/space.css找到以下代码: /*页...

[PHP]实用函数6第1/2页

//寄出电子邮件到指定的邮件地址 to,subject 表示主题,message 为信件内容。额外的选项 additional_headers&n...

用Json实现PHP与JavaScript间数据交换的方法详解

JSON(JavaScript Object Notation) 是一种轻量级的数据交换格式。简而论之,不管是xml还是json都是为了方便在客户端与服务器端交互数据的中转站,特别是用于...

阿里云的WindowsServer2016上部署php+apache

阿里云的WindowsServer2016上部署php+apache

一、说明:项目需要在阿里云的WindowsServer2016上部署web环境,已经安装了Mysql,所以就不用一键安装(如phpstudy或者wamp来安装web环境了),就独立安装了...