【问题标题】:Session handling class strange behaviour会话处理类奇怪的行为
【发布时间】:2016-05-10 18:28:22
【问题描述】:

我正在使用以下类来处理会话:

class DBHandler implements SessionHandlerInterface {

public function open($save_path, $name) {
    try {
        DBCxn::get();
        return true;
    } catch(PDOException $e) {
        return false;   
    }
}

public function close() {
    return true;    
}

public function destroy($session_id) {
    $sth = DBCxn::get()->prepare("DELETE FROM sessions WHERE session_id = ?");
    $sth->execute(array($session_id));
    return true;
}

public function gc($maxlifetime) {
    $sth = DBCxn::get()->prepare("DELETE FROM sessions WHERE session_id = ?");
    $sth->execute(array(time() . $maxlifetime));    
    return true;    
}

public function read($session_id) {
    $sth = DBCxn::get()->prepare("SELECT session_data FROM sessions WHERE session_id = ?");
    $sth->execute(array($session_id));
    $rows = $sth->fetchALL(PDO::FETCH_NUM);
    if (count($rows) == 0) {
        return '';  
    }
    else {
        return $rows[0][0]; 
    }   
}

public function write($session_id, $session_data) {
    $sth = DBCxn::get()->prepare("UPDATE sessions SET session_data = ?, last_update = NOW() WHERE session_id = ?");
    $sth->execute(array($session_data, $session_id));
    if ($sth->rowCount() == 0) {
        $sth = DBCxn::get()->prepare("INSERT INTO sessions (session_id, session_data, last_update) VALUES (?, ?, NOW())");
        $sth->execute(array($session_id, $session_data));           
    }


  }
}

session_set_save_handler(new DBHandler);

然后我开始会话,然后使用 switch(通过 get 变量或 ajax 访问)将主 div 的内容包含在 index.html 中。 php.

在通过 ajax 访问时,该开关具有以下验证:

if(!isset($_SESSION)) 
{ 
    session_start();
} 

if(isset($_SESSION['l'])) {

在 index.php 结束时,使用 session_write_close();

关闭会话

DB 表对唯一会话 ID 有约束。

出于某种原因,并且仅在某些时候我收到以下错误:

致命错误:带有消息的未捕获异常“PDOException” 'SQLSTATE [23000]:完整性约束违规:1062 重复条目 '312505097fb815255103447952d0af61' 用于 file_path:99 中的键 'PRIMARY'' 堆栈跟踪:#0 file_path(99): PDOStatement->execute(Array) #1 【内部函数】:DBHandler->write('312505097fb8152...', 'login|i:1;') #2 file_path(185): session_write_close() #3 {main} 在 file_path:99 中抛出

file_path:99 是前面提到的类中的以下行 "$sth->execute(array($session_id, $session_data));"

file_path:185 是 index.php 末尾的 session_write_close()

什么可能导致这个错误?

【问题讨论】:

  • 嗯,错误的意思是您已经将 session_id 设置为显示的数字。出现错误的地方可能是插入命令。但这对您来说应该很容易调试 - 只需放入一些 ECHO 语句,这样您就可以看到正在发生的事情,也可以对错误使用 try-catch,这样您就可以进行回溯以找出问题发生的位置。现在看起来你没有发现任何错误。所以这是找出你的代码有什么问题的第一步。

标签: php mysql ajax session


【解决方案1】:

写入函数正在生成重复错误。如果会话数据与在 DB 中存储会话数据相同,则 $sth->rowCount() 将始终返回值 0。因此,它尝试插入具有相同 session_id 的会话数据并产生重复错误。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-06-27
    • 2014-03-03
    • 2017-08-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多