名站导航为爱好php程序的朋友们提供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 PhP程序SESSID = ?'; $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 PhP程序SESSID = ?'; $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 PhP程序SESSID = ?'; $stmt = $this->_pdo->prepare($sql); $stmt->execute(array(time(), $data, $id)); } } else { if (!empty($data)) { $sql = 'INSERT INTO session (PhP程序SESSID, 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 PhP程序SESSID = ?'; $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程序的知识就说到这里希望可以帮助需要的朋友。,如何决策项目是否要用PhP程序框架来开发