How to access cookie values on different paths of the same domain using PHP?

后端 未结 5 970
暖寄归人
暖寄归人 2020-12-11 16:34

Can a parameter of path be added to $_COOKIE[]?

5条回答
  •  伪装坚强ぢ
    2020-12-11 17:11

    While the HTTP client (ie: browser) does not send back the path that the cookie was set to, PHP actually makes assumptions about cookies with regards to its $_COOKIE array.

    If you set two cookies with the same name, one with the value "first-value" with path / and the second with the value "second-value" with path /test, a browser following the recommended - but not required - behaviour from the RFC will send back both values to you. When you access a URL under the /test path, the browser sends this:

    Cookie: name=second-value, name=first-value
    

    The "problem" is that PHP only reads the first value - $_COOKIE['name'] will only contain the value "second-value" with no hint that "first-value" exists. If you need access to both values, you need to parse the value of $_SERVER['HTTP_COOKIE'] yourself - this will contain "name=second-value, name=first-value" for the above example. Note that "second-value" is first in line because it was set with a longer path. Please note that the RFC does not guarantee this behaviour, it only says that HTTP clients SHOULD do this.

提交回复
热议问题