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

yipeiwu_com5年前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编程中数组的指针的使用

要使用数组中的元素,就需要数组的定位。定位的实现需要借助数组指针来完成。PHP中有很多函数可以移动数组指针。下面将给大家介绍几个。 将指针移动到下一个数组位置next() next()函...

ThinkPHP模型详解

模型定义,默认情况下,ThinkPHP的模型类是位于/Home/Model/目录之下,模型类通常需要继承系统的\Think\Model类或其子类,下面是一个Home\Model\User...

Wordpress 相册插件 NextGEN-Gallery 添加目录将中文转为拼音的解决办法

NextGEN Gallery是Wordpress中著名的相册插件,遗憾的是不支持中文等unicode字符,本文将介绍如何将目录转换为拼音(添加图集时)。 以NextGEN 1.6.2为...

php检查字符串中是否包含7位GSM字符的方法

本文实例讲述了php检查字符串中是否包含7位GSM字符的方法。分享给大家供大家参考。具体分析如下: 下面的代码检查一个字符串是否包含任何7位GSM字符。它对短信平台上工作的人非常有用。...

php写入、删除与复制文件的方法

本文实例讲述了php写入、删除与复制文件的方法。分享给大家供大家参考。具体如下: 1. 写入: <?php $filename = "Test//file.txt";...