手机
当前位置:查字典教程网 >编程开发 >php教程 >Session保存到数据库的php类分享
Session保存到数据库的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();

}

【Session保存到数据库的php类分享】相关文章:

PHP 中的类

关于PHP中操作MySQL数据库的一些要注意的问题

桌面中心(一)创建数据库

一个连接两个不同MYSQL数据库的PHP程序

php备份数据库类分享

PHP数据库操作面向对象的优点

Session的工作方式

分页显示Oracle数据库记录的类之二

多数据表共用一个页的新闻发布

PHP如何透过ODBC来存取数据库

精品推荐
分类导航