Why is it that if I create a cookie on http://www.example.com and check it on example.com, the cookie doesn’t exist there? I am planning to just use .htaccess redirect non-www to a www domain. But how do I solve this?
Why is it that if I create a cookie on www.example.com and check it
Share
Browsers are the main culprit here, not PHP. They store by domain, and don’t know that
wwwis a special case; from their perspective,www.mydomain.comandmydomain.comare different strings, and therefore have different security policies. However, there is something you can do.When setting the cookie, use
.mydomain.com(with the leading dot). This will tell your user’s browser make the cookie accessible tomydomain.comand all subdomains, includingwww. PHP’s setcookie has the argument$domain, but it’s fifth on the list, so you may need to set$expireand$pathto their default values in order to get at it.For consistency, however, you may wish to consider rerouting all web traffic to a specific domain, i.e. send
mydomain.comtraffic towww.mydomain.com, or vice-versa. My vague knowledge of SEO (edit if incorrect) tells me that it’s helpful so as not to have duplicate content, and it saves you all such authentication issues. Additionally, if you store assets on a subdomain, having cookies on there slows down traffic by having to transport it each time, so storing application cookies only onwwwearns you that speed boost.Here is a tutorial on how to accomplish such a redirect in Apache.