php讀寫cookies無效問題解決辦法

來源:互聯網
上載者:User

今天本地調試,有個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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.