检查是否存在PHP Cookie,如果未设置其值 [英] Check if a PHP cookie exists and if not set its value

查看:247
本文介绍了检查是否存在PHP Cookie,如果未设置其值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在一个多语种的网站工作,所以我尝试这个办法:

I am working on a multilingual site so I tried this approach:

echo $_COOKIE["lg"];
if (!isset($_COOKIE["lg"]))
    setcookie("lg", "ro");
echo $_COOKIE["lg"];

这个想法是,如果客户端没有 lg cookie(因此,他们第一次访问此网站),然后为该用户设置一个cookie lg = ro

The idea is that if the client doesn't have an lg cookie (it is, therefore, the first time they've visited this site) then set a cookie lg = ro for that user.

一切正常,除非我第一次进入这个页面,第一个和第二个 echo 什么都不返回。只有当我刷新页面是Cookie组,然后双方回声打印RO的字符串,我期待着。

Everything works fine except that if I enter this page for the first time, the first and second echo return nothing. Only if I refresh the page is the cookie set and then both echo print the "ro" string I am expecting.

如何设置此cookie以便在用户的第一次访问/页面加载时从第二个 echo 查看其值?应该是无需刷新页面,或创建一个重定向。

How can I set this cookie in order to see its value from the second echo on the first visit/page load of the user? Should be without needing to refresh the page or create a redirect.

推荐答案

您无法根据 PHP手册


在饼干已经确定,它们可以在与$ _COOKIE下一页
负载或$ HTTP_COOKIE_VARS阵列访问。

Once the cookies have been set, they can be accessed on the next page load with the $_COOKIE or $HTTP_COOKIE_VARS arrays.

这是因为cookie是在响应头部发送到浏览器,然后浏览器必须发送回下一个请求。这是为什么他们只能在第二页加载。

This is because cookies are sent in response headers to the browser and the browser must then send them back with the next request. This is why they are only available on the second page load.

当您调用 setcookie()时,也可​​以通过设置 $ _ COOKIE

But you can work around it by also setting $_COOKIE when you call setcookie():

if(!isset($_COOKIE['lg'])) {
    setcookie('lg', 'ro');
    $_COOKIE['lg'] = 'ro';
}
echo $_COOKIE['lg'];

这篇关于检查是否存在PHP Cookie,如果未设置其值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆