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判断浏览器的类型和语言的函数代码

我们经常看到有一些网站上面会显示出你目前使用的浏览器类型和使用的语言,比如显示的是:您使用的浏览器为 IE6,繁体字。看起来是不是很炫。 其实这样的功能不难实现,无非就是判断浏览器的类型...

php文件包含的几种方式总结

php文件包含的几种方式总结

四种语句 PHP中有四个加载文件的语句:include、require、include_once、require_once。 基本语法 require:require函数一般放在PHP脚...

php中fgetcsv()函数用法实例

本文实例讲述了php中fgetcsv()函数用法。分享给大家供大家参考。具体方法如下: fgetcsv是一个简单的生成excel文档的函数,从 PHP 4.3.5 起,fgetcsv()...

PHP 遍历XP文件夹下所有文件

复制代码 代码如下:<meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <?ph...

解析php中获取url与物理路径的总结

在这里我想总结一下取得地址栏内URL及文件所属的我更路径的一些信息:运用$_SERVER[ ]我们可以来完成许多事情:它是一个包含头部(headers),路径信息及脚本位置的数组,数组的...