我確信這個主題已經被解決過,但我似乎無法找到解決我的問題的適當解決方案,但我確定這不是唯一的。設置cookie然後刷新頁面,PHP
所以我得到,你不能設置一個cookie,並期望在不刷新頁面的情況下使用。所以我想知道我的選擇是什麼。
我有一組簡單的鏈接,通過將cookie設置爲該用戶的語言首選項來更改頁面上的語言。我需要檢測該cookie以分配變量,以便我可以將頁面輸出更改爲指定語言。
所以,當按下按鈕時,它會向URL欄發送一個get變量,然後設置cookie。刷新頁面後,我得到我想要的。
基本上,我需要傳遞GET變量,然後刷新頁面。我怎樣才能做到這一點?
我的PHP代碼:
// if someone is trying to change the language
if(isset($_GET['lang']))
{
// change the cookie value to that language
$value = $_GET['lang'];
}
// elseif they are not trying to change the language, and a cookie is already set
elseif(isset($_COOKIE['language_pref']))
{
// maintain the value of the language set in the cookie
$value = $_COOKIE['language_pref'];
}
// if get nor cookie is set
else
{
// set default language to english
$value = 'en_US';
}
$name = 'language_pref';
// cookie expires in 2 years
$expireDate = time() + (2 * 365 * 24 * 60 * 60);
$path = '/';
$domain = 'example.com';
$secure = false; //only transmit the cookie if a HTTPS connection is established
$httponly = true; //make cookie available only for the HTTP protocol (and not for JavaScript)
setcookie($name, $value, $expireDate, $path, $domain, $secure, $httponly);
我的HTML:
<a href="?lang=zh_CN">ZH</a>
<a href="?lang=en_US">EN</a>
您不需要刷新 - 信息,顯示哪種語言已通過URL參數傳遞給您。 – CBroe
@CBroe我需要將頁面上的所有內容更改爲不同的語言,所以我肯定需要刷新頁面。 – compguy24
_「我需要頁面上的所有內容」__ - 你爲什麼不已經擁有它? – CBroe