0

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.

redcrow
  • 1,743
  • 3
  • 25
  • 45
  • How are you inspecting it the first time? The `$_COOKIE` superglobal won't get the new value from `setcookie()` until after a reload. That is expected. – Michael Berkowski Oct 27 '14 at 15:50

1 Answers1

1

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;
}
Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592
  • Yes, I thought that $_COOKIE[$name] was set after calling setcookie(), but now, thanks to your reply, I've understood that $_COOKIE[$name] gets the saved cookie from the browser. – redcrow Oct 27 '14 at 16:02