php读写cookies无效问题解决办法
对于cookies读写操作我们如果域名配置没配置好那么可能只有一个域名要使用,像www.phprm.com与phprm.com后者是包括前者的哦,下面来给大家举个例子。
今天本地调试,有个cookies死活都写不进去,环境如下:
域名:phprm.com
浏览器:chrome34
<?php header("Content-type: text/html; charset=utf-8"); if (isset($_COOKIE['test'])) { echo '获取到的cookies是:'.$_COOKIE['test']; } elseif (setcookie('test', 'okh', time() + 3600, '/', '.phprm.com')) { echo '设置cookies:test'; } else { echo '什么都没有'; } ?>
用phprm.com访问,上面这段代码在chrome下一直设置成功,但是却一直都没记录。找了半天原因,一朋友从手册上告诉我:
The domain that the cookie is available to. Setting the domain to "www.example.com" will make the cookie available in the www subdomain and higher subdomains. Cookies available to a lower domain, such as "example.com" will be available to higher subdomains, such as "www.example.com". Older browsers still implementing the deprecated » RFC 2109 may require a leading . to match all subdomains.
于是我做了这么一个调整:
用www.phprm.com进行访问
修改之前的代码为
1
setcookie('test', 'okh', time() + 3600, '/', 'www.phprm.com')
这下正常设置,也正常记录了。
但是存在2个问题:
如何设置不带WWW的域名的cookies呢?比如:phprm.com
设置www.phprm.com虽然能在www.phprm.com下使用,但是却不能在phprm.com下使用,如何设置cookies使其通用呢?
通过求助,得知原因如下:
这个域名特殊。火狐、chrome不认为 www.phprm.com 是 phprm.com 的二级域名:
var eTLDService = Components.classes["@mozilla.org/network/effective-tld-service;1"] .getService(Components.interfaces.nsIEffectiveTLDService); eTLDService.getBaseDomain(gBrowser.selectedTab.linkedBrowser.currentURI); /* www.phprm.com */ phprm.com 在 effective_tld_names.dat 文件中列出来了: a.org b.cn
原来是这么一个小问题,困扰了我一天,原本是为了方便,所以将这个域名作为自己本地开发用,结果出现这个情况,只好将phprm.com修改为1a.com
教程链接:http://www.phprm.com/code/61172.html
随意转载~但请保留教程地址★