2014-02-14 125 views
0

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

您不需要刷新 - 信息,显示哪种语言已通过URL参数传递给您。 – CBroe

+0

@CBroe我需要将页面上的所有内容更改为不同的语言,所以我肯定需要刷新页面。 – compguy24

+0

_“我需要页面上的所有内容”__ - 你为什么不已经拥有它? – CBroe

回答

0

好了,所以这里是你的页面的样子:

> 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 

您将拥有正确的语言并且无需刷新页面。

+0

所以我已经添加了我的PHP的后 - 你不觉得我遵循你的订单? – compguy24

0

我认为你所缺少的是链接到包含此php的url的按钮。

如果你的按钮,但你已经实现它有一个包含该页面的URL的href,那么当你点击它时,你将刷新页面并将cookie的内容读入$ value。

尝试关闭PHP标签,然后补充说:

<a href='PAGE_URL_HERE'>button</a> 
+0

,因此按钮位于站点每个页面上的导航栏内,因此我需要重新加载当前页面。不幸的是,当我使用一些js重新加载当前页面时,它会一直添加get变量,所以如果有人点击了?lang ='cats',并且它会重新加载?lang ='cats',然后他们再次更改语言,我得到了吗?lang ='cats'?land ='dogs',这不是一个被认可的cookie。 – compguy24

+0

所有你需要的是2个包含“PAGE_URL?lang = cats”和“PAGE_URL?lang = dogs”的href链接。点击它们会将其设置为一个或另一个。 – Steven1978

+0

WTF有JS与此有关吗?只需制作该链接,以便在每个页面上链接_to同一个page_,只有添加了该语言的GET参数。 – CBroe

0

你可以使用PHP的页眉或包含在仅在报表符合所有的条件被执行代码的其他组成部分的JavaScript,因为所有你想要的是刷新页面设置cookie后或读取

0

清除它这个PHP的,这让我根据当前页面翻译得到的变量,并与存储的cookie其随后所有的网页

if(isset($value)) 
{ 
    $language = $value; 

} 
else 
{ 
    $language = $_COOKIE['language_pref']; 
}