I don't remember having many problems using Cookies in the past but I was playing around and encountered some unexpected results.
(i'm running on localhost, hence my domain setting)
<?php
$sessionCookie = rand();
setcookie("crav_auto_login_cookie", $sessionCookie, false,"/crav/", false);
echo "Cookie Set<br/>";
echo "Cookie equals: ".$_COOKIE["crav_auto_login_cookie"]."<br/>";
echo "should equal: ". $sessionCookie;
?>
This will yield in the following output:
Cookie Set
Cookie equals: 457718770
should equal: 318511886
I am obviously missing something, but not sure why the values are different. Is it because cookies are loaded on page cal开发者_运维问答l, and $_COOKIE["crav_auto_login_cookie"]
is returning the results from the instance called when the page is opened and not reflecting the newly set value? If that is the case, then why?
setcookie
sets up headers to send back to the client in order to set a cookie. The new cookie won't be accessible in the $_COOKIE
array (which contains cookies sent from the client) until the next request.
Here is a simplified progression of events when a user accesses your page:
- User's browser sends a request to your server. This request contains headers, including what cookies are set for that user for your domain. PHP fills the
$_COOKIE
(as well as$_GET
,$_POST
, etc.) array based on the data in this request. - The server parses the user's request, and sets up a response. This response begins with response headers (including any headers you set yourself through
header
, and also headers for cookies set throughsetcookie
). All headers must precede any page output (as you may have encountered, PHP will give you an error if you try to send more headers after you've begun outputting page content). - The server sends the page content (in reality, the headers and content are part of the same transmission).
- The connection between the server and client closes (let's ignore AJAX for the purposes of this discussion).
- The client parses the headers and content it received, sets cookies as necessary, and renders the page (in reality, this could very well happen in serial with receiving the page).
So by the time the set-cookie header is received and processed by the client, the client is already done communicating with the server, which is why the cookie won't appear to PHP until the next request.
From PHP.net's setcookie documentation under "Common Pitfalls":
Cookies will not become visible until the next loading of a page that the cookie should be visible for. To test if a cookie was successfully set, check for the cookie on a next loading page before the cookie expires.
you could overwrite the superglobal directly.
$sessionCookie = rand();
setcookie("crav_auto_login_cookie", $sessionCookie, false,"/crav/", false); $_COOKIE["crav_auto_login_cookie"] = $sessionCookie;
echo "Cookie Set";
echo "Cookie equals: ".$_COOKIE["crav_auto_login_cookie"];
echo "should equal: ". $sessionCookie;
精彩评论