PHP类分享:session保存到数据库


下面是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(); 

}
来源:豆芽博客,地址:http://www.aichengxu.com/article/PHP/567_1.html保留原文链接,是开源分享的开始.


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值