开发者

PHP Session variable isset(..)=1 after session_start()

I guess I am not understanding the scope of session variables, or the session itself, in PHP, hence this question:

This is my code

  if(session_id()!=""){
  echo "Getting rid of session"."</br>";
  session_destroy();
 }
 echo "Before session_start(): ".isset($_SESSION["first_date_of_week"])."</br>";
 session_start();
 echo "After session_start(): ".isset($_SESSION["first_date_of_week"])." ".$_SESSION["first_date_of_week"]->format("Y-m-d")."</br>";

The output is:

Before session_start():
After session_start(): 1 2011-01-09

How come that when doing the isset(..) on the session variable it is set directly after starting the session, even though I haven't even used it or set it yet? It does, however, still have the same value as before.

Also, session_id()="" since the if-clau开发者_高级运维se is never triggered. I never kill the session, how come it is set to ""? I.e. I refresh the page and expects the session to still be alive.

Using the isset(..) function is then pretty useless testing if it has been set already...

Thanks in advance!

/Niklas


There are a couple of problems with the code:

  1. The test !session_id()=="" is wrong because ! has a higher precedence than ==. It should be written as session_id() != "". Due to implicit conversions it should work correctly, but I can't say it's anything else than a bug.
  2. session_destroy only works if called after session_start.

Now, here's what happens exactly:

  1. You test for an active session. Since there's none, the test fails and session_destroy is never called (it would do nothing even if it were called).
  2. You test for the existence of $_SESSION["first_date_of_week"]. Since there's no active session, isset return false.
  3. You start the session. $_SESSION["first_date_of_week"] now becomes available, but only because you had set it on some earlier session, in code that you don't show.

Try this code to get a better handle on what's going on:

$logout = true; // play with this
session_start();
if ($logout) {
    session_destroy();
    echo "Logged out.";
    die;
}

if (!isset($_SESSION['counter'])) {
    $_SESSION['counter'] = 1;
}
else {
    ++$_SESSION['counter'];
}

echo "The counter value is ".$_SESSION['counter'];
die;


Remember that session_start doesn't start a new session, just starts "the session". So if you've set something (and you haven't destoryed it, see @Jon 's answer), then you'll get your session back :)


session_start();
if(isset(session_id())) {
    session_destroy();
}
$_SESSION['data'] = "something";
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜