This question already has an answer here:
I have this code in a php page:
if(!isset($_COOKIE[$cookie_name])) {
if(!setcookie($cookie_name, mt_rand(), time() + (86400 * 30), "/")) {
die("[ERROR COOKIE] Failed to set cookie!");
}
}
If I don't have any cookie set in my browser the first time the page is loaded $_COOKIE[$cookie_name]
is set to 0
. Afterwards, if I reload the page, it is set to a random number as expected.
So far I just make a workaround like this:
if(!isset($_COOKIE[$cookie_name])) {
if(!setcookie($cookie_name, mt_rand(), time() + (86400 * 30), "/")) {
die("[ERROR COOKIE] Failed to set cookie!");
}
if($_COOKIE[$cookie_name] == 0) {
echo "<meta http-equiv=\"refresh\" content=\"0; url=./\" />";
die();
}
}
but what I'd like to understand is why the first time setcookie() defaults to 0
.
</div>
It doesn't. It defaults to NULL
, because it hasn't been set.
setcookie
merely adds the Set-Cookie
header to the list of headers to be sent to the browser. It is a convenience shortcut for header("Set-Cookie: ...");
that does the formatting for you. It does not modify the $_COOKIE
superglobal.
You can, of course, do it yourself:
function updatecookie($name,$val,$exp=0,$path="/",$domain="",$secure=false,$httponly=false) {
$ret = setcookie($name,$val,$exp,$path,$domain,$secure,$httponly);
if( $ret) $_COOKIE[$name] = $val;
return $ret;
}