問題描述
我在一個(gè)多語言網(wǎng)站上工作,所以我嘗試了這種方法:
I am working on a multilingual site so I tried this approach:
echo $_COOKIE["lg"];
if (!isset($_COOKIE["lg"]))
setcookie("lg", "ro");
echo $_COOKIE["lg"];
這個(gè)想法是,如果客戶端沒有 lg
cookie(因此,這是他們第一次訪問該站點(diǎn)),則設(shè)置一個(gè) cookie lg = ro
用于該用戶.
The idea is that if the client doesn't have an lg
cookie (it is, therefore, the first time they've visited this site) then set a cookie lg = ro
for that user.
一切正常,只是如果我第一次進(jìn)入這個(gè)頁面,第一個(gè)和第二個(gè) echo
什么都不返回.只有當(dāng)我刷新頁面時(shí)才會(huì)設(shè)置 cookie,然后 echo
都會(huì)打印我期望的ro"字符串.
Everything works fine except that if I enter this page for the first time, the first and second echo
return nothing. Only if I refresh the page is the cookie set and then both echo
print the "ro" string I am expecting.
如何設(shè)置此 cookie 以便在用戶第一次訪問/頁面加載時(shí)從第二個(gè) echo
中查看其值?應(yīng)該不需要刷新頁面或創(chuàng)建重定向.
How can I set this cookie in order to see its value from the second echo
on the first visit/page load of the user? Should be without needing to refresh the page or create a redirect.
推薦答案
答案
你不能根據(jù)PHP手冊:
設(shè)置 cookie 后,即可在下一頁訪問它們加載 $_COOKIE 或 $HTTP_COOKIE_VARS 數(shù)組.
Once the cookies have been set, they can be accessed on the next page load with the $_COOKIE or $HTTP_COOKIE_VARS arrays.
這是因?yàn)?cookie 是在響應(yīng)標(biāo)頭中發(fā)送到瀏覽器的,然后瀏覽器必須將它們與下一個(gè)請求一起發(fā)送回去.這就是它們僅在第二次頁面加載時(shí)可用的原因.
This is because cookies are sent in response headers to the browser and the browser must then send them back with the next request. This is why they are only available on the second page load.
但是你也可以通過在調(diào)用 setcookie()
時(shí)設(shè)置 $_COOKIE
來解決這個(gè)問題:
But you can work around it by also setting $_COOKIE
when you call setcookie()
:
if(!isset($_COOKIE['lg'])) {
setcookie('lg', 'ro');
$_COOKIE['lg'] = 'ro';
}
echo $_COOKIE['lg'];
這篇關(guān)于檢查 PHP cookie 是否存在,如果不存在則設(shè)置其值的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!