Zacky112
Zacky112

Reputation: 8879

Question on PHP cookies

I came across the snippet below:

setcookie('foo', 'v1', time() + 60*60*24, '/');
setcookie('foo', 'v2');

Upvotes: 2

Views: 256

Answers (3)

Peter Kruithof
Peter Kruithof

Reputation: 10764

I think this is not intended. The second cookie call will overwrite the original set cookie. After the first call there is no knowing if browser support is available, as no input from the browser is received when processing a script. A cookie is sent as a HTTP header, and sent back by the browser on consecutive requests.

Upvotes: 1

Manaf Abu.Rous
Manaf Abu.Rous

Reputation: 2417

The above example will simply overwrite the first cookie with the second one. If you want to update a cookie to store a newer value, you can overwrite its value.

Two cookies may have the same name if they were set for different domains or paths. example :

<?php 
setcookie("testcookie", "value1forhost", time(), "/", ".domain.com", 0, true);
setcookie("testcookie", "value2forsubdom", time(), "/", "subdom.domain.com", 0, true);
?>

Upvotes: 3

&#193;lvaro Gonz&#225;lez
&#193;lvaro Gonz&#225;lez

Reputation: 146370

The v1 vs v2 part makes it look like a trick to detect a cookie handling bug in the browser: if foo equals v1, the browser did not process the value change.

It'd be interesting to know about the code context.

Edit

Will it set 2 cookies or will it overwrite

It depends on where you call the script from. A setcookie() call without a path sets a cookie for current path (where path is an URL path, not the internal file system path). So a call from http://example.com/ would create a single cookie and a call from http://example.com/somewhere/inside/ would crate two separate cookies, one for / and one for /somewhere/inside/.

Upvotes: 1

Related Questions