PHP - funny behaviour of cookie variables and session variables

后端 未结 3 1267
-上瘾入骨i
-上瘾入骨i 2021-01-26 17:10

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

相关标签:
3条回答
  • 2021-01-26 17:25

    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.

    0 讨论(0)
  • 2021-01-26 17:30
    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.

    0 讨论(0)
  • 2021-01-26 17:31

    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 讨论(0)
提交回复
热议问题