PHP cookie问题 - www或没有www [英] PHP cookie problem - www or without www

查看:183
本文介绍了PHP cookie问题 - www或没有www的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么如果我在www.example.com上创建一个Cookie并在example.com上进行检查,该Cookie是否不存在?我计划只使用 .htaccess 将非www重定向到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?

推荐答案

浏览器是这里的主要原因,他们按域存储,不知道 www 是一种特殊情况;从他们的角度来看, www.mydomain.com mydomain.com 是不同的字符串,因此具有不同的安全策略。

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.

设置cookie时,使用 .mydomain.com 前导点)。这将告诉您的用户浏览器使 mydomain.com 和所有子域(包括 www )可访问Cookie。 PHP的 setcookie 有参数 $ domain ,但它是列表中的第五个,因此您可能需要将 $ expire $ path 设置为其默认值,以便得到它。

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');

但是,为了一致性,您可以考虑将所有网络流量重新路由到特定域, mydomain.com 流量到 www.mydomain.com ,反之亦然。我对SEO的模糊知识(如果不正确,请编辑)告诉我,这是有帮助的,以免有重复的内容,它会为您节省所有这样的身份验证问题。此外,如果您将资源存储在子域中,在其上放置Cookie会减慢流量,因为每次都要传输它,因此只在 www 上存储应用程序Cookie可以提高速度。

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.

这里有一个教程,介绍如何在Apache中完成此类重定向。

这篇关于PHP cookie问题 - www或没有www的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆