PHP Session保存到数据库
2011-11-06 12:24
441 查看
<?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 = !emptyempty($_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 (!emptyempty($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封装的数据库保存session功能类
- 关于php session被保存在数据库中的一个小问题
- php采用数据库保存session
- 将PHP中的Session保存到数据库中
- PHP数据库保存session会话
- PHP SESSION 保存到数据库
- 如何使用数据库实现PHP保存session
- PHP数据库保存session会话
- PHP-数据库保存session
- php将session保存到数据库的类实例
- php将session保存到数据库的类实例
- PHP类分享:session保存到数据库
- PHP中使用数据库保存session
- PHP-应用数据库保存自定义SESSION
- php session 保存数据库
- nodejs中cookie,session保存内存,缓存,数据库中
- php session存数据库
- php中如何同时使用session和cookie来保存用户登录信息
- php文件上传并将其路径保存到数据库