首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >PHP Session类和$_SESSION数组

PHP Session类和$_SESSION数组
EN

Stack Overflow用户
提问于 2010-01-05 20:48:15
回答 4查看 7.7K关注 0票数 2

我已经实现了这个自定义的PHP Session类,用于将会话存储到MySQL数据库中:

代码语言:javascript
复制
class Session
{
    private $_session;
    public $maxTime;
    private $database;
    public function __construct(mysqli $database)
    {
        $this->database=$database;
        $this->maxTime['access'] = time();
        $this->maxTime['gc'] = get_cfg_var('session.gc_maxlifetime');

        session_set_save_handler(array($this,'_open'),
                array($this,'_close'),
                array($this,'_read'),
                array($this,'_write'),
                array($this,'_destroy'),
                array($this,'_clean')
                );

        register_shutdown_function('session_write_close');

        session_start();//SESSION START

    }

    public function _open()
    {
        return true;
    }

    public function _close()
    {
        $this->_clean($this->maxTime['gc']);
    }

    public function _read($id)
    {
        $getData= $this->database->prepare("SELECT data FROM 
                                            Sessions AS Session
                                            WHERE Session.id = ?");
        $getData->bind_param('s',$id);
        $getData->execute();

        $allData= $getData->fetch();
        $totalData = count($allData);
        $hasData=(bool) $totalData >=1;

        return $hasData ? $allData['data'] : '';
    }

    public function _write($id, $data)
    {
        $getData = $this->database->prepare("REPLACE INTO
            Sessions
            VALUES (?, ?, ?)");
        $getData->bind_param('sss', $id, $this->maxTime['access'], $data);

        return $getData->execute();
    }

    public function _destroy($id)
    {
        $getData=$this->database->prepare("DELETE FROM
            Sessions
            WHERE id = ?");
        $getData->bind_param('S', $id);
        return $getData->execute();
    }

    public function _clean($max)
    {
        $old=($this->maxTime['access'] - $max);

        $getData = $this->database->prepare("DELETE FROM Sessions WHERE access < ?");
        $getData->bind_param('s', $old);
        return $getData->execute();
    }
}

它工作得很好,但我不知道如何正确地访问$_SESSION数组:例如:

代码语言:javascript
复制
$db=new DBClass();//This is a custom database class
$session=new Session($db->getConnection());
if (isset($_SESSION['user']))
{
    echo($_SESSION['user']);//THIS IS NEVER EXECUTED!
}
else
{
    $_SESSION['user']="test";
    Echo("Session created!");
}

在每次页面刷新时,似乎$_SESSION['user']以某种方式被“重置”,我可以应用什么方法来防止这种行为?

EN

回答 4

Stack Overflow用户

回答已采纳

发布于 2010-01-05 21:20:53

mysqli_stmt::fetch()不返回表示行的数组,它只返回true或false。因此,您在_read()中的代码

代码语言:javascript
复制
$allData= $getData->fetch();
$totalData = count($allData);
$hasData=(bool) $totalData >=1;
return $hasData ? $allData['data'] : '';

不能工作。$allData将为truefalse,并且没有数组元素$allData['data']

http://docs.php.net/mysqli-stmt.fetch说:

将预准备语句的结果提取到mysqli_stmt_bind_result()绑定的变量中。

代码语言:javascript
复制
  public function _read($id)
  {
    $getData= $this->database->prepare("SELECT data FROM
      Sessions AS Session
      WHERE Session.id = ?
    ");
    if ( false===$getData ) {
      // now what?
    }

    $getData->bind_param('s',$id);
    $getData->bind_result($data);
    if ( false===$getData->execute() ) {
      // now what?
    }
    return  $getData->fetch() ? $data : '';
  }
票数 1
EN

Stack Overflow用户

发布于 2010-05-12 22:51:20

这是更新的代码!:-)现在它完全工作了!

代码语言:javascript
复制
<?php
class session {
    private $_session;
    public $maxTime;
    private $db;
    public function __construct() {
        $this->maxTime['access'] = time();
        $this->maxTime['gc'] = 21600; //21600 = 6 hours

        //it is session handler
        session_set_save_handler(array($this,'_open'),
                array($this,'_close'),
                array($this,'_read'),
                array($this,'_write'),
                array($this,'_destroy'),
                array($this,'_clean')
                );

        register_shutdown_function('session_write_close');

        session_start();//SESSION START
    }

    private function getDB() {
        $mysql_host = 'your_host';
        $mysql_user = 'user';
        $mysql_password = 'pass';
        $mysql_db_name = 'db_name';


        if (!isset($this->db)) {
            $this->db = new mysqli($mysql_host, $mysql_user, $mysql_password, $mysql_db_name);
            if (mysqli_connect_errno()) {
                printf("Error no connection: <br />%s\n", mysqli_connect_error());
                exit();
            }
        }

        return $this->db;
    }

    // O_O !!!
    public function _open() {
        return true;
    }


    public function _close() {
        $this->_clean($this->maxTime['gc']);
    }

    public function _read($id)  {       
        $stmt= $this->getDB()->prepare("SELECT session_variable FROM table_sessions 
                                            WHERE table_sessions.session_id = ?");
        $stmt->bind_param('s',$id);
        $stmt->bind_result($data);
        $stmt->execute();
        $ok = $stmt->fetch() ? $data : '';
        $stmt->close();
        return $ok;
    }

    public function _write($id, $data) {    
        $stmt = $this->getDB()->prepare("REPLACE INTO table_sessions (session_id, session_variable, session_access) VALUES (?, ?, ?)");
        $stmt->bind_param('ssi', $id, $data, $this->maxTime['access']);
        $ok = $stmt->execute();
        $stmt->close();
        return $ok;     
    }

    public function _destroy($id) {
    $stmt=$this->getDB()->prepare("DELETE FROM table_sessions WHERE session_id = ?");
    $stmt->bind_param('s', $id);
    $ok = $stmt->execute();
    $stmt->close();
    return $ok;
    }

    public function _clean($max) {
    $old=($this->maxTime['access'] - $max);
    $stmt = $this->getDB()->prepare("DELETE FROM table_sessions WHERE session_access < ?");
    $stmt->bind_param('s', $old);
    $ok = $stmt->execute();
    $stmt->close();
    return $ok;
    }
}
?>

以下是会话表:

代码语言:javascript
复制
CREATE TABLE IF NOT EXISTS `table_sessions` (
  `session_id` varchar(50) NOT NULL,
  `session_variable` text NOT NULL,
  `session_access` decimal(15,0) NOT NULL,
  PRIMARY KEY  (`session_id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
票数 3
EN

Stack Overflow用户

发布于 2010-01-05 20:52:42

也许你需要先start a session一下?

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/2006064

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档