Why is it that if I create a cookie on 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?
views:
291answers:
4because php translates www.mydomain.com differently from mydomain.com. If the domains are not 100% identical the cookie wont match.
And I'm sure the browser also looks for 100% match of the domain name before allowing servers to overwrite them.
Just use .htaccess to redirect. It's the only SURE way to tackle this in all browsers.
Browsers are the main culprit here, not PHP. They store by domain, and don't know that www
is a special case; from their perspective, www.mydomain.com
and mydomain.com
are 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 to mydomain.com
and all subdomains, including www
. PHP's setcookie has the argument $domain
, but it's fifth on the list, so you may need to set $expire
and $path
to their default values in order to get at it.
setcookie('name', 'value', time()+3600, '/', '.mydomain.com');
For consistency, however, you may wish to consider rerouting all web traffic to a specific domain, i.e. send mydomain.com
traffic to www.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 on www
earns you that speed boost.
Here is a tutorial on how to accomplish such a redirect in Apache.
I believe you can set the cookie at example.com (really .example.com) and it will be sent if they go to www.example.com, but not vice versa. This standard security policy is to prevent users' private data from being sent to unintended servers.
Personally, I use virtualhosts in my apache2.conf:
<VirtualHost *:80>
ServerName example.com
RedirectMatch (.*) http://www.example.com$1
</VirtualHost>
... in this example, everyone trying to load e.g. http://example.com/index.html is redirected to http://www.example.com/index.html.
setcookie("CookieName", "value", time()+3600, "/", ".mydomain.com");