zoukankan      html  css  js  c++  java
  • PHP Session保存到数据库

    <?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();
    }
  • 相关阅读:
    May 24th 2017 Week 21th Wednesday
    May 23rd 2017 Week 21st Tuesday
    全球顶尖大学的UX课程资源,英文!
    如何设计出一款出色的结账表单
    快速完成网页设计,10个顶尖响应式HTML5网页模板助你一臂之力
    界面设计中如何增强CTA按钮召唤力?
    10个实用的UX设计作品推销小窍门
    UX术语详解:任务流,用户流,流程图以及其它全新术语
    让你不再恋家的9款小众时尚的酒店网站设计
    聊聊原型设计中的团队管理功能
  • 原文地址:https://www.cnblogs.com/liangle/p/2512538.html
Copyright © 2011-2022 走看看