今天本地調試,有個cookies死活都寫不進去,環境如下:
網域名稱:111cn.net
瀏覽器:chrome34
代碼:
| 代碼如下 |
複製代碼 |
header("Content-type: text/html; charset=utf-8"); if (isset($_COOKIE['test'])) { echo '擷取到的cookies是:'.$_COOKIE['test']; } elseif (setcookie('test', 'okh', time() + 3600, '/', '.111cn.net')) { echo '設定cookies:test'; } else { echo '什麼都沒有'; }
|
用111cn.net訪問,上面這段代碼在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.111cn.net進行訪問
修改之前的代碼為
1
setcookie('test', 'okh', time() + 3600, '/', 'www.111cn.net')
這下正常設定,也正常記錄了。
但是存在2個問題:
如何設定不帶WWW的網域名稱的cookies呢?比如:111cn.net
設定www.111cn.net雖然能在www.111cn.net下使用,但是卻不能在111cn.net下使用,如何設定cookies使其通用呢?
通過求助,得知原因如下:
這個網域名稱特殊。Firefox、chrome不認為 www.111cn.net 是 111cn.net 的次層網域:
| 代碼如下 |
複製代碼 |
var eTLDService = Components.classes["@mozilla.org/network/effective-tld-service;1"] .getService(Components.interfaces.nsIEffectiveTLDService); eTLDService.getBaseDomain(gBrowser.selectedTab.linkedBrowser.currentURI); /* www.111cn.net */
|
111cn.net 在 effective_tld_names.dat 檔案中列出來了:
a.org
b.cn
原來是這麼一個小問題,困擾了我一天,原本是為了方便,所以將這個網域名稱作為自己本地開發用,結果出現這個情況,只好將111cn.net修改為1a.com