欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2022-06-20 18:45:58
复制代码 代码如下:
复制代码 代码如下:

<?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();
}