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

查看:25
本文介绍了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?

推荐答案

浏览器是罪魁祸首,而不是 PHP.他们按域存储,不知道 www 是特例;从他们的角度来看,www.mydomain.commydomain.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 会降低流量,因为每次都必须传输它,因此仅将应用 cookie 存储在 www 上可以为您带来速度提升.

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天全站免登陆