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中rename()函数的妙用讲解

大家都知道,rename()函数可以对文件或目录进行重命名的操作。其实它还可以做很多事情。 熟悉unix的朋友应该知道shell命令mv,它相当与win32的移动,而且移动的同时可进行重...

PHP实现redis限制单ip、单用户的访问次数功能示例

本文实例讲述了PHP实现redis限制单ip、单用户的访问次数功能。分享给大家供大家参考,具体如下: 有时候我们需要限制一个api或页面访问的频率,例如单ip或单用户一分钟之内只能访问多...

php 运行效率总结(提示程序速度)

1,在函数中,传递数组时 使用 return 比使用 global 要高效 比如 function userloginfo($usertemp){ $detail=explode("|"...

ionCube 一款类似zend的PHP加密/解密工具

PHP本身没有带有ionCube loader模块, 必须到ionCube网站下载。ionCube loader是免费的,但是Encoder的价格就比较昂贵(起价$199)。 下面要介...

破解图片防盗链的代码(asp/php)测试通过

php版的代码比较简单:复制代码 代码如下: <?php $p=$_GET['p']; $pics=file($p); for($i=0;$i< count($pics);$...