开发者

PHP session looks corrupt

This is used to get a list of previously served markers from session:

session_start();
if(!isset($_SESSION['markers'])) {
    $_SESSION['markers'] = array(0);
    $list = '0';
} else {
    $list = implode(', ', $_SESSION['markers']);
}

I use $list to get markers not already served:

SELECT * FROM `markers` WHERE {other conditions} AND `marker_id` NOT IN($list) 

Then for each row returned I add the marker id to session:

while ($row = mysqli_fetch_assoc($result)){
  $_SESSION['markers'][] = (int) $row['marker_id'];
  ...
}

However, after serving some markers (say 8, 36) the session looks corrupt. var_dump($_SESSION); outputs:

array(1) {
  ["markers"]=>
  &array(3) {
    [0]=>
    int(0)
    [1]=>
    int(8)
    [2]=>
    int(36)
  }
}

I say it is corrupt because when I manually make a similar array (codepad here) the output does not show a & in the third line - it is array(3), not &array(3). What is causing this?

开发者_高级运维Update

@Marc B is hinting the session is not corrupt. His take is that we just have a variable ($_SESSION), containing a reference to an array ($markers), instead of the array itself; and that is not a corrupt variable. Well, the session is corrupt for session usage purposes. Two signs:

  1. A second call to the same script (in which I guess the else route is taken) results in a fatal error: Fatal error: Cannot use object of type DOMElement as array in ... on line 47. Line 47 is where we attempt to add a new marker id to the array: $_SESSION['markers'][] = (int) $row['marker_id'];
  2. When I try to unserialize the actual contents of session file it fails (codepad here).


If you have register_globals to On, global variables associated to $_SESSION variables are references. Source: http://php.net/manual/en/reserved.variables.session.php


Quoting it from php manual http://php.net/manual/en/reserved.variables.session.php

Please note that if you have register_globals to On, global variables associated to $_SESSION variables are references, so this may lead to some weird situations.

<?php

session_start();

$_SESSION['test'] = 42;
$test = 43;
echo $_SESSION['test'];

?>

Load the page, OK it displays 42, reload the page... it displays 43.

The solution is to do this after each time you do a session_start() :

<?php

if (ini_get('register_globals'))
{
    foreach ($_SESSION as $key=>$value)
    {
        if (isset($GLOBALS[$key]))
            unset($GLOBALS[$key]);
    }
}

?>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜