[英]Set cookie and then refresh page, PHP
我确定这个主题以前已经解决过,但是我似乎找不到解决我问题的适当方法,我确信这不是唯一的。
因此,我知道您无法设置cookie并期望在不刷新页面的情况下使用它。 所以我想知道我的选择是什么。
我有一组简单的链接,它们通过将cookie设置为该用户的语言首选项来更改页面上的语言。 我需要检测该Cookie来分配一个变量,以便随后可以将页面输出更改为指定的语言。
因此,当按下按钮时,它会将get变量发送到URL栏,然后设置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>
好的,这是您页面的外观:
> Read cookie and get the language
> Read GET variable and SET COOKIE
> Print out stuff in their language
您只是在以错误的顺序进行操作。 如果按此顺序执行操作:
> Read GET variable and SET COOKIE
> Read cookie and get the language
> Print out stuff in their language
您已经有了正确的语言,无需刷新页面。
我认为您所缺少的只是链接到包含此php的URL的按钮。
但是,如果您实现了按钮,则该按钮具有包含该页面URL的href,那么当您单击该按钮时,将刷新页面并将Cookie的内容读入$ value。
尝试关闭php标签,然后添加:
<a href='PAGE_URL_HERE'>button</a>
您可以使用代码的else组件中包含的php标头或JavaScript,仅在该语句满足所有条件时才执行,因为您想要的只是在设置和/或读取Cookie之后刷新页面。
使用此php清除了它,这使我可以根据get变量以及存储的cookie的所有后续页面来翻译当前页面
if(isset($value))
{
$language = $value;
}
else
{
$language = $_COOKIE['language_pref'];
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.