开发者

Question on PHP cookies

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?


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);
?>


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜