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
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.
session_start()
) and you're using undefined constant test
, however PHP is "intelligent" enough to figure out you mean a string "test"
.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.