douxuexiao1748 2014-10-21 09:30
浏览 58
已采纳

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

I am implementing a simple session manager with PHP and MongoDB. But somehow the $_SESSION is empty on next page, assigned value on first page though..

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();

Next i have created 2 new scripts to test this sessionManager Mongo_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>

If you had faced the same problem before, and got the solution for that, it would be very helpful for me to learn the MongoDB and PHP web development. Thank you in advance.

  • 写回答

1条回答 默认 最新

  • douou5933 2014-10-22 01:05
    关注

    You have two issues:

    First, you are using two different variable names; "expire_at" and "expired_at" which is clearly causing the query to fail.

    Second, I think your logic is wrong for the "read" of expire/expired_at which should probably be:

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

    ...Your expired_at value was calculated as time+LIFESPAN, therefore you only need to compare it to time() to see if it is in the future.

    Hope this helps.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器