php自定义session用mysql来存储session会话

代码语言:php

所属分类:会话

代码描述:php自定义session用mysql来存储session会话

代码标签: mysql 存储 session 会话

下面为部分代码预览,完整代码请点击下载或在bfwstudio webide中打开

<?php
class MysqlSession implements SessionHandlerInterface {
    private $link;
    private $lifetime;
    public function open($savePath, $session_name) {
        $this->lifetime = get_cfg_var('session.gc_maxlifetime');
        $this->link = mysqli_connect('localhost', 'user', 'pwd', 'sess_database');
        mysqli_query($this->link, "SET names UTF8");
        mysqli_query($this->link, "CREATE TABLE IF NOT EXISTS `sessions` ( `session_id` varchar(32) NOT NULL, `session_expires` int(10) unsigned DEFAULT NULL, `session_data` text, PRIMARY KEY (`session_id`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8");
        if ($this->link) {
            return true;
        }
        return false;
    }
    public function close() {
        mysqli_close($this->link);
        return true;
    }
    public function read($session_id) {
        $sql = "SELECT * from sessions where session_id='{$session_id}'
              and session_expires >".time();
        $result = mysqli_query($this->link, $sql);
        if (mysqli_num_rows($result)) {
            return mysqli_fetch_array($result)['session_data'];
        }
        return "";
    }
    public function write($session_id, $session_data) {
        $newExp = time()+$this->lifetime;
        //首先查询是否存在指定的session_id,如果存在相当于更新数据,否则是第一次,则写入数据
        $sql = "SELECT * from sessions where session_id={'$sessi.........完整代码请登录后点击上方下载按钮下载查看

网友评论0