Arno
Arno

Reputation: 375

Cookie with no name in PHP?

I was trying to set cookie name from a variable, and I accidentally deleted the variable declaration, which lead to an intersting discovery. Consider the code below:

setcookie('', 'value', time()+10);  

I assumed that this code shouldn't work since we need to declare a name for the cookie, and respectively should output an error, but instead it sets the cookie with name that is contained in the value, and the value of the cookie is equal to an empty string '' instead:

var_dump($_COOKIE);  // array (size=1) 'value' => string '' (length=0)
setcookie('', 'value', time()+10);  
echo (int)isset($_COOKIE['value']);  // 1

Can someone explain please why that happens? I'm just trying to think that potentially there could be a situation when this might happen and cause a lot of confusion, although you should check everything for mistakes in your code.

Upvotes: 1

Views: 516

Answers (2)

Florian
Florian

Reputation: 2874

Just a guess: Looking at the source of setcookie the format used to build the Set-Cookie header line is Set-Cookie: %s=%s. So, i'm not a C programmer, but maybe C's snprintf doesn't replace the first parameter name (which would be an empty string) and starts replacing the format-string with the second additional parameter value as the first.

Upvotes: 0

Thibault Henry
Thibault Henry

Reputation: 841

The cookies are stocked like a GET parameters.

For exemple :

setCookie('a', 'A');
setCookie('b', 'B');

Will be stored as :

a=A&b=B

I assume that, if the key is empty, an url_encode will display this :

setCookie('', 'A');
setCookie('b', 'B');

A&b=B

Wich can be read as :

A = "";
b = "B";

Upvotes: 1

Related Questions