会话变量不会在使用MongoDB的php中保留下一页的值



我正在用PHP和MongoDB实现一个简单的会话管理器。但不知何故,$_SESSION在下一页上是空的,尽管在第一页上赋值。。

class SessionManager
{
//name of collection where sessions will be stored
const COLLECTION = 'sessions';
//Expire session after 10 mins in inactivity
const SESSION_TIMEOUT = 600;
//Expire session after 1 hour
const SESSION_LIFESPAN = 3600;
//name of session cookie
const SESSION_NAME = 'mongosessid';
const SESSION_COOKIE_PATH = '/';
const SESSION_COOKIE_DOMAIN = '';
private $_mongo;
private $_collection;
//Represent the current session
private $_currentSession;
function __construct()
{
    $this->_mongo = DBConnection::instantiate();
    $this->_collection = $this->_mongo->getCollection(SessionManager::COLLECTION);
    session_set_save_handler(
        array(&$this, 'open'),
        array(&$this, 'close'),
        array(&$this, 'read'),
        array(&$this, 'write'),
        array(&$this, 'destroy'),
        array(&$this, 'gc')
    );
    //Set session garbage collection period
    ini_set('session.gc_maxlifetime', SessionManager::SESSION_LIFESPAN);
    //Set session cookie configurations
    session_set_cookie_params(
        SessionManager::SESSION_LIFESPAN,
        SessionManager::SESSION_COOKIE_PATH,
        SessionManager::SESSION_COOKIE_DOMAIN
    );
    //Replace  'PHPSESSID' with 'mongosessid' as the
    // session name
    session_name(SessionManager::SESSION_NAME);
    session_cache_limiter('nocache');
    register_shutdown_function('session_write_close');
    // start the session
    session_start();
}
public function open($path, $name)
{
    return true;
}
public function close()
{
    return true;
}
public function read($sessionId)
{
    $query = array(
        'session_id' => $sessionId,
        'timedout_at' => array('$gte' => time()),
        'expire_at' => array('$gte' => time() - SessionManager::SESSION_LIFESPAN)
    );
    $result = $this->_collection->findOne($query);
    $this->_currentSession = $result;
    if (!isset($result['data'])) {
        return '';
    }
    return $result['data'];
}
public function write($sessionId, $data)
{
  //  $expired_at = time() + self::SESSION_TIMEOUT;
    $new_obj = array(
        'data' => $data,
        'timedout_at' => time() + self::SESSION_TIMEOUT,
        'expired_at' => (empty($this->_currentSession)) ?
                time() + SessionManager::SESSION_LIFESPAN
                : $this->_currentSession['expired_at']
    );
    $query = array('session_id' => $sessionId);
    $this->_collection->update(
        $query,
        array('$set' => $new_obj),
        array('upsert' => true)
    );
    return true;
}
public function destroy($sessionId)
{
    $this->_collection->remove(array('session_id' => $sessionId));
    return true;
}
public function gc()
{
    $query = array('expired_at' => array('$lt' => time()));
    $this->_collection->remove($query);
    return true;
}
}
// initiate the session
$session = new SessionManager();

接下来,我创建了两个新脚本来测试这个sessionManagerMongo_session1.php

<?php
 // Session started by requiring the script
 require('session.php');
 // Generate random number
 $random_number = rand();
 //Put the number into session
 $_SESSION['random_number'] = $random_number;
?>
<!doctype html>
<html lang="en">
 <head>
  <meta charset="UTF-8">
  <link rel="stylesheet" href="css/style.css"/>
  <title>Using SessionManager ... Page 1</title>
  </head>
  <body>
     <p> Random number generated
        <span style="font-weight: bold">
            <?php echo $_SESSION['random_number']; ?>
        </span>
     </p>
     <p>
        PHP session id
        <span style="text-decoration: underline">
            <?php echo session_id(); ?>
        </span>
    </p>
    <a href="mongo_session2.php">Go to Next page</a>
  </body>
</html>

Mongo_session2.php

<?php
    // Session started by requiring the script
    require('session.php');
?>
<!doctype html>
<html lang="en">
  <head>
     <meta charset="UTF-8">
     <link rel="stylesheet" href="css/style.css"/>
     <title>Using SessionManager ... Page 2</title>
  </head>
  <body>
       <h2>Using the SessionManager.. Page 2</h2>
       <p>The random number generated in previous page is still
         <span style="font-weight: bold">
           <?php
              echo "<pre>";
               print_r($_SESSION);
              echo "</pre>";
           ?>
         </span>
        </p>
        <p>
         PHP session id
          <span style="text-decoration: underline;">
            <?php echo session_id(); ?>
          </span>
         </p>
   </body>
</html>

如果您以前也遇到过同样的问题,并找到了解决方案,那么学习MongoDB和PHP web开发将对我非常有帮助。提前谢谢

您有两个问题:

首先,您使用两个不同的变量名;"expire_at"one_answers"expired_at",这显然会导致查询失败。

其次,我认为您对expired_at的"读取"逻辑是错误的,它可能应该是:

'expire_at' => array('$gte' => time())

您的expired_at值被计算为时间+LIFEPAN,因此您只需要将其与时间()进行比较,看看它是否在未来。

希望这能有所帮助。

相关内容

  • 没有找到相关文章

最新更新