域名和cookie
偶然想到一个问题:www.g.cn能把cookie设置为.g.cn,那么www.com.cn能设置把cookie设置为.com.cn吗?

试验结果:不能。因为浏览器知道www.com.cn的后缀是.com.cn而不是.cn,所以禁止设置cookie。
因为浏览器内置了域名后缀列表。todo:如果以后出现新的后缀,而老浏览器没法更新列表,岂不是会允许设置cookie?

extension后缀 一级域名 二级域名
www.g.cn .cn g.cn *.g.cn
www.com.cn .com.cn www.com.cn *.www.com.cn
www.google.com.cn .com.cn google.com.cn *.google.com.cn

www.example.com能读取到.example.com的cookie吗?
能。
www.example.com能读取到example.com的cookie吗?
不能。todo:把www.example.com和example.com做SSO,即可防止cookie带到static.example.com。
example.com能读取到www.example.com的cookie吗?
答:不能。
setcookie('a', 'aa', time() + 1234, '/', 'example.com'); 设置的cookie是 .example.com 还是 example.com的?
答:是.example.com的。
如果想设置example.com的cookie,需要使用setcookie('default', 'default', time() + 1234, '/');。
cookie的设置和读取范围:

HTTP请求域名 一级域名 cookie可设置(并可读取)的范围 cookie不可设置 cookie不可读取
example.com example.com example.com,.example.com www.example.com www.example.com
www.example.com example.com www.example.com,.www.example.com,.example.com example.com example.com
g.com.cn g.com.cn g.com.cn,.g.com.cn .com.cn  
www.com.cn www.com.cn www.com.cn,.www.com.cn .com.cn

设置cookie代码:
实现代码如下:

<?php
setcookie('default', 'default', time() + 1234, '/');
setcookie('a', 'aa', time() + 1234, '/', 'example.com');
setcookie('b', 'bb', time() + 1234, '/', '.example.com');
?>

读取cookie代码:
实现代码如下:

<?php
var_dump($_COOKIE);
?>

结果截图:

以上就是【域名和cookie问题(域名后缀)】的全部内容了,欢迎留言评论进行交流!

赞(0) 踩(0)
发表我的评论

最新评论

  1. 暂无评论