2

Why are cookies being set twice for my website? One set of cookies is stored for "www.example.com" and the same set is being stored for "example.com".

Sarah Hamed
  • 119
  • 2
  • 4
  • 10
  • Cookies are bound to domains. If you browse both, then you'll get cookies for both. โ€“ mario May 19 '12 at 11:48

1 Answers1

5

Most likely, you are allowing access to your site via both domain names example.com and www.example.com and you have not specified the domain name for which your cookie should be set. The fifth parameter to setcookie() specifies domain, so set it to example.com only. That will make it available to the higher domain www.example.com as well.

setcookie('key', 'value', time(), '/path', 'example.com');

Via URL rewriting, you can force all users of your site to one or the other of those domains before the cookie is set, but that is merely a solution for consistency of user experience, not a way to manage cookies.

From the docs:

domain

The domain that the cookie is available to. Setting the domain to 'www.example.com' will make the cookie available in the www subdomain and higher subdomains. Cookies available to a lower domain, such as 'example.com' will be available to higher subdomains, such as 'www.example.com'. Older browsers still implementing the deprecated ยป RFC 2109 may require a leading . to match all subdomains.

Community
  • 1
  • 1
Michael Berkowski
  • 267,341
  • 46
  • 444
  • 390
  • If I set that fifth parameter to example.com, would it create a problem for people trying to access cookies through the www.example.com ? Or it would work for both? โ€“ Sarah Hamed May 19 '12 at 11:50
  • Just wanted to point out this question/answer if people are curious [how browser cookies interpret the domain](http://stackoverflow.com/a/1063760/1168661) โ€“ aug Oct 26 '15 at 17:09