Next Oct 12 PreviousSome cookies are best served raw
Suppose we have the following two scripts:
<?php
// save as 'setcookievalue.php'
setrawcookie("sum", "1+1=3");
header("Location: showcookievalue.php");
?>
<?php
// save as 'showcookievalue.php'
echo $_COOKIE["sum"];
?>
What will be printed in your browser window if you naviagate to 'setcookievalue.php'.
A: "1+1=3"
B: "1 1=3"
C: Nothing: the cookie will not be set because invalid data was given.
D: Warning: unvalid assingment in showcookievalue.php on line 3
Answer
PHP gives you two specialized functions to set a cookie: setcookie()
and setrawcookie()
. The first one URL encodes the cookie value before setting it, the other does not and thereby making yourself responsible for properly encoding the cookie value.
The superglobal $_COOKIE
lets you retrieve cookie values but note that it's actually the counterpart of setcookie()
. Before PHP populates the $_COOKIE
array PHP URL decodes the cookie data.
So when you want to use $_COOKIE
please use setcookie()
too. Otherwise you'll have a mismatch and that's what is happening in this question: The string "1+1=3" was set as the cookie value and when PHP sets this value in the $_COOKIE
array PHP will URL decode the value. The URL encoded value for a space (" ") is "+", so when you URL decode "1+1=3" you'll end up with "1 1=3". Therefore answer B is the correct answer.
So what's setrawcookie()
for, you'll ask. The example would have worked if the value was URL encoded first, but then what's the benefit of using urlencode()
and setrawcookie()
over just using setcookie()
?
Well, in this case none. But note that there is no official 'cookie value encoding' and URL encoding just works well for cookie values. However other encodings such as base64 can and might be used as well. setrawcookie()
is there to help you out if you'll ever need to use a different encoding, but normally there is no reason to use it.