我确信这个主题已经被解决过,但我似乎无法找到解决我的问题的适当解决方案,但我确定这不是唯一的。设置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