简体   繁体   English

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

[英]Check if a PHP cookie exists and if not set its value

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"];

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.这个想法是,如果客户端没有lg cookie(因此,这是他们第一次访问该站点),则为该用户设置 cookie lg = ro

Everything works fine except that if I enter this page for the first time, the first and second echo return nothing.一切正常,除了如果我第一次进入这个页面,第一个和第二个echo显什么都不返回。 Only if I refresh the page is the cookie set and then both echo print the "ro" string I am expecting.仅当我刷新页面时才设置 cookie,然后两者都echo显打印我期望的“ro”字符串。

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?如何设置此 cookie 以便在用户第一次访问/页面加载时从第二个echo显中查看其值? Should be without needing to refresh the page or create a redirect.应该不需要刷新页面或创建重定向。

Answer 回答

You can't according to the PHP manual : 你不能根据PHP手册

Once the cookies have been set, they can be accessed on the next page load with the $_COOKIE or $HTTP_COOKIE_VARS arrays. 设置cookie后,可以使用$ _COOKIE或$ HTTP_COOKIE_VARS数组在下一页加载时访问它们。

This is because cookies are sent in response headers to the browser and the browser must then send them back with the next request. 这是因为cookie在响应头中发送到浏览器,然后浏览器必须在下一个请求时将它们发回。 This is why they are only available on the second page load. 这就是为什么它们仅在第二页加载时可用。

Work around 解决

But you can work around it by also setting $_COOKIE when you call setcookie() : 但是你可以通过在调用setcookie()时设置$_COOKIE来解决它:

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

Cookies are only sent at the time of the request, and therefore cannot be retrieved as soon as it is assigned (only available after reloading). Cookie 在请求时发送,因此无法在分配后立即检索(仅在重新加载后可用)。

Once the cookies have been set, they can be accessed on the next page load with the $_COOKIE or $HTTP_COOKIE_VARS arrays. 设置cookie后,可以使用$ _COOKIE或$ HTTP_COOKIE_VARS数组在下一页加载时访问它们。

If output exists prior to calling this function, setcookie() will fail and return FALSE. 如果在调用此函数之前存在输出,则setcookie()将失败并返回FALSE。 If setcookie() successfully runs , it will return TRUE. 如果setcookie() 成功运行 ,它将返回TRUE。 This does not indicate whether the user accepted the cookie . 并不表示用户是否接受该cookie。

Cookies will not become visible until the next loading of a page that the cookie should be visible for. 在下一次加载可以看到cookie 的页面之前 ,Cookie不会显示。 To test if a cookie was successfully set, check for the cookie on a next loading page before the cookie expires. 要测试cookie是否已成功设置,请在cookie过期前检查下一个加载页面上的cookie。 Expire time is set via the expire parameter. 过期时间通过expire参数设置。 A nice way to debug the existence of cookies is by simply calling print_r($_COOKIE);. 调试cookie存在的一种好方法是简单地调用print_r($ _ COOKIE);.

Source 资源

If you set a cookie with php setcookie you can see the set and the value of the cookie, as an example, with the developer tools of firefox just in time .如果你用php setcookie设置cookie,你can see the set and the value ,例如,用firefox的developer tools just in time

But you need to reload/load the same/next page if you wanna read, get or check the cookie and the value inside to work with that cookie in PHP .但是,如果您想阅读、获取或检查 cookie 和其中的值to work with that cookie PHP中的该 cookie,则But you need to reload/load相同/ page

With this example you can choose if you wanna reload the same page with PHP , HTML or JAVASCRIPT .通过此示例,您可以choose是否要使用PHPHTMLJAVASCRIPT reload同一页面。

If the cookie is not accepted or cookies are disabled, a loading loop is obtained and the browser stops loading the page.如果 cookie 不被接受或 cookies 被禁用,则获得加载循环并且浏览器停止加载页面。

LONGVERSION WITH PHP 'header' RELOAD SAME PAGE : LONGVERSION WITH PHP 'header' RELOAD SAME PAGE

<?php

$COOKIE_SET     = [
     'expires'  => '0'
    ,'path'     => '/'
//  ,'domain'   => 'DOMAIN'
    ,'secure'   => 'true'
    ,'httponly' => 'true'
    ,'samesite' => 'Strict'
    ];
    
$COOKIE_NAME    = "MYCOOKIE";
$COOKIE_VALUE   = "STACKOVERFLOW";
    
if(!isset($_COOKIE[$COOKIE_NAME])){
    setcookie($COOKIE_NAME, $COOKIE_VALUE, $COOKIE_SET);
    // YOU NEED TO RELOAD THE PAGE ONCE
    // WITH PHP, HTML, OR JAVASCRIPT
    // UNCOMMENT YOUR CHOICE
    
    // echo '<meta http-equiv="refresh" content="0;URL=">';
    // echo '<script>window.location.replace("");</script>';
    header("Location: ");
    exit;
  }
else{
    echo ($_COOKIE[$COOKIE_NAME]);
}
  
?> 

SHORTVERSION WITH PHP 'header' RELOAD SAME PAGE : SHORTVERSION WITH PHP 'header' RELOAD SAME PAGE

if(!isset($_COOKIE['MYCOOKIE'])){
    setcookie('MYCOOKIE', 'STACKOVERFLOW');
    header("Location: ");
    exit;
}

echo ($_COOKIE['MYCOOKIE']);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM