Reputation: 12328
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 call, 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?
Upvotes: 4
Views: 488
Reputation: 3757
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;
Upvotes: 1
Reputation: 94103
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:
$_COOKIE
(as well as $_GET
, $_POST
, etc.) array based on the data in this request.header
, and also headers for cookies set through setcookie
). 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).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.
Upvotes: 5
Reputation: 3841
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.
Upvotes: 1