自定义 Session 数据保存

当项目访问量大的时候,我们就不能采取php默认session存储方式了(php默认为文件存储),这个时候我们就要自己实现session数据存储。好在php提供了重写session数据的接口给我们。下面就是简单的用mysql存储session数据案例。

<?php
/**
 * @Author: Aaron
 * @Last Modified by:   Aaron
 */

class MysqlSessionHandle implements SessionHandlerInterface
{
    protected $_pdo = null;

    public function close()
    {
        $this->_pdo = null;
    }

    public function destroy($sessionID)
    {
        $sql = "delete from session where id = :sessionID";
        $stm = $this->_pdo->prepare($sql);
        $stm->bindParam(':sessionID',$sessionID,PDO::PARAM_STR,strlen($sessionID));
        $stm->execute();
    }

    public function gc($maxlifetime)
    {
        $sql = "delete from session where createTime < :maxlifetime";
        $stm = $this->_pdo->prepare($sql);
        @$stm->bindParam(':maxlifetime',$maxlifetime,PDO::PARAM_INT);
        $stm->execute();
    }

    public function open($savePath,$sessionName)
    {
        $dsn = 'mysql:dbname=test;host=127.0.0.1';
        $user = 'root';
        $password = 123456;
        try {
            $this->_pdo = new PDO($dsn,$user,$password);
        } catch (\Exception $e) {
            // 连接异常 可以在次记录日志
        }
    }

    public function read($sessionID)
    {
        $sql = "select * from session where id = :sessionID";
        $sth = $this->_pdo->prepare($sql);
        $sth->bindParam(':sessionID',$sessionID,PDO::PARAM_STR,strlen($sessionID));
        $sth->execute();
        $result = $sth->fetch(PDO::FETCH_ASSOC);
        return $result['data'];
    }

    public function write($sessionID,$data)
    {
        $sql = 'select * from session where id = :sessionid';
        $sth = $this->_pdo->prepare($sql);
        $sth->bindParam(':sessionid',$sessionID,PDO::PARAM_STR,strlen($sessionID));
        $sth->execute();
        $result = $sth->fetchAll(PDO::FETCH_ASSOC);
        if (empty($result)) {
            $sql = "insert into session values(:sessionID , :data , :time)";
        }else{
            $sql = "update session set data = :data, createTime = :time where id = :sessionID";
        }
        $sth = $this->_pdo->prepare($sql);
        // 绑定参数值 并 设定参数类型
        $sth->bindParam(':sessionID',$sessionID,PDO::PARAM_STR,strlen($sessionID));
        @$sth->bindParam(':time',time());
        $sth->bindParam(':data',$data,PDO::PARAM_STR,strlen($data));
        $result = $sth->execute();
    }
}
$myse = new MysqlSessionHandle();
session_set_save_handler($myse,true);
session_start();
$_SESSION['name'] = 'Aaron';
$_SESSION['age'] = 27;
$_SESSION['profession'] = 'PHP工程师';
Aaron
Aaron
《L03 构架 API 服务器》
你将学到如 RESTFul 设计风格、PostMan 的使用、OAuth 流程,JWT 概念及使用 和 API 开发相关的进阶知识。
《L02 从零构建论坛系统》
以构建论坛项目 LaraBBS 为线索,展开对 Laravel 框架的全面学习。应用程序架构思路贴近 Laravel 框架的设计哲学。
讨论数量: 0
(= ̄ω ̄=)··· 暂无内容!

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!