设置cookie,然后刷新页面,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);

我的网页:

<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 的按钮。

如果您的按钮已实现,则它有一个包含此页面网址的 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'];
}

最新更新