tags:

views:

55

answers:

3

I came across the snippet below:

setcookie('foo', 'v1', time() + 60*60*24, '/');
setcookie('foo', 'v2');
  • What is the effect of setting 2 cookies with same name but different values?
  • Is it common in practice?
  • Where is it used?
+1  A: 

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/.

Álvaro G. Vicario
+1 it really looks like that the cookie `foo` should have the value `v1` on all pages and `v2` only on the current page.
Felix Kling
+3  A: 

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);
?>
Manaf Abu.Rous
+1  A: 

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.

Peter Kruithof