Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
812 views
in Technique[技术] by (71.8m points)

.htaccess - PHP cookie problem - www or without www

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...