检查 PHP cookie 是否存在,如果不存在则设置其值

2021-12-21 00:00:00 cookies php setcookie

我在一个多语言网站上工作,所以我尝试了这种方法:

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,然后 echo 都会打印我期望的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 后,即可在下一页访问它们加载 $_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'];

相关文章