开发者

PHP - funny behaviour of cookie variables and session variables

I wrote a little PHP script below to demonstrate my question. Run the code below like this: http://localhost/test.php?test=10, then run http://localhost/test.php?test=11, then http://localhost/test.php?test=12, etc. You will see that the number echo'ed to your screen is always 1 digit behind the url number?! Maybe because I cant a cookie and immediately read the same cookie?


//If query string has $test, store in session, and cookie for later. 
if($_GET[test]){
  $_SESSION['test'] = $_GET[test];
  setcookie("test", $_GET[test], time()+60*60*24*30*12*10); //10 years
}

//If user comes back later, then get $test from cookie
if (isset($_COOKIE["test"])){
  $_SESSION['test'] = $_COOKIE["test"];
}

echo "session test: " . $_SESSION['test'];

Later, I solved the problem with the foll开发者_运维知识库owing code, but solving it is not good enough, I want to know WHY this happened!

This solved it:


if($_GET[cid]){
  setcookie("campaignid", $_GET[cid], time()+60*60*24*30*12*10); //10 years
  $_SESSION['campaignid'] = $_GET[cid];
}elseif (isset($_COOKIE["campaignid"])){
  $_SESSION['campaignid'] = $_COOKIE["campaignid"];
}


Maybe because I cant a cookie and immediately read the same cookie?

Exactly. The cookie you sent is available in $_COOKIE array only in the next request, because the $_COOKIE superglobal array is filled with the data, that comes in the client's request. And at first request it is nothing.


  1. Technically you didn't start a session (session_start()) and you're using undefined constant test, however PHP is "intelligent" enough to figure out you mean a string "test".
  2. What's exactly the question?

    Maybe because I cant a cookie and immediately read the same cookie?

    Yes, that's true. You've just proved it.


In your first snippet you are calling setcookie(). This sends a HTTP header to the browser. PHP does not update the $_COOKIES variable when you call setcookie(). The $_COOKIES variable is updated on the next script invocation, when the cookie is returned by the browser.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜