Page 1 of 1

COOKIE Value Passed By Reference?

Posted: Fri Nov 02, 2007 5:43 pm
by tomprogers
Here's what I'm going for:

1 - copy specific GET vars into COOKIE (using header() )
2 - redirect user to URL with no GET string
3 - copy values out of COOKIEs for use by script
4 - destroy COOKIES

I have this code:

Code: Select all

$keepers = array('x', 'y', 'z'); // a list of specific GET variables I want to preserve

foreach($keepers as $k)
{
   if(isset($_COOKIE[$k])) // this variable exists as a cookie
   {
      $kept[$k] = $_COOKIE[$k]; // copy value into a script var
      header("Set-Cookie: {$k}=; Discard"); // destroy the cookie
   }
}

var_dump($kept);
die();
When I call this script and pass it x as a GET var, I get almost what I want.
$kept contains a named key for x, but the value is blank. If I comment out the cookie-destroying header, $kept has a value for x. I'm getting the behavior I would expect if I were creating a reference to $_COOKIE['x'] instead of passing its value.

I also tried modifying the code, like so:

Code: Select all

... if(isset($_COOKIE[$k]))
   {
      $o .= $k . '=' . $_COOKIE[$k] . '<br />'; // check the value before destroying the cookie
      header("Set-Cookie: {$k}=; Discard"); // destroy the cookie
      $o .= $k . '=' . $_COOKIE[$k] . '<br />'; // check the value after destroying the cookie
   }
print($o);
If I run that code, $o reveals that the value of $_COOKIE[$k] is blank, both before and after the header call. If I comment the header call, the value appears both before and after the commented line.

The way I understand things, the first line should have a value for the cookie, and the second should not. Instead, it's like statement order doesn't matter, or (as I mentioned earlier) the variable is being passed by reference. I have even tried writing the value into an output buffer and grabbing the value from that, but I get the same results: clearing the cookie anywhere in the script prevents any code from seeing the value, even before it is cleared.

If anyone has an explanation why this is the case, I'd love to hear it.

Posted: Fri Nov 02, 2007 6:51 pm
by Kieran Huggins
The $_COOKIE[] array is read/write, you should treat it as such rather than sending the headers manually.

Since cookies are synced with the browser through HTTP headers, if you send the header manually it won't show up in the COOKIE array until the next sync, when it's pulled in from the next browser request headers.

If you write to the $_COOKIE array it will automagically send the same headers to the browser you're sending, as well as retain a local copy of the cookie in the array for the current request.