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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…