php $_COOKIE isset

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9415282/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 06:46:02  来源:igfitidea点击:

php $_COOKIE isset

phpcookies

提问by Frank

I am using this code to set a cookie and then see if they exist

我正在使用此代码设置 cookie,然后查看它们是否存在

setcookie("token", "value", time()+60*60*24*100, "/");
setcookie("secret", "value", time()+60*60*24*100, "/");
setcookie("key", "value", time()+60*60*24*100, "/");

if (!isset($_COOKIE['token']) || !isset($_COOKIE['secret']) || !isset($_COOKIE['key'])) {

// do something because one of the cookies were not set

}

Even though all three of the cookies were set in my browser, it still runs the if()statement. Via the process of elimination I have discovered the middle cookie !isset($_COOKIE['secret'])seems to cause the if()statement to run even though the cookie secretwas set in my browser. The script says it has not been set when I look at my browser and it has been set. Can you think of any reason why php is saying it wasn't set?

即使所有三个 cookie 都在我的浏览器中设置,它仍然运行该if()语句。通过消除过程,我发现中间 cookie!isset($_COOKIE['secret'])似乎导致if()语句运行,即使 cookiesecret是在我的浏览器中设置的。当我查看浏览器时,脚本说它尚未设置并且已设置。你能想到 php 说它没有设置的任何原因吗?

回答by xdazz

setcookieonly defines a cookie to be sent along with the rest of the HTTP headers, and they can be accessed on the next page load with the $_COOKIE. With your code, the HTTP headers are not be sent.

setcookie只定义了一个 cookie 与其余的 HTTP 标头一起发送,并且可以在下一个页面加载时使用$_COOKIE. 使用您的代码,不会发送 HTTP 标头。

You just need setcookiewhen a cookie is not set. Like:

您只需要setcookie在未设置 cookie 时使用。喜欢:

if (!isset($_COOKIE['token'])) {
    setcookie("token", "value", time()+60*60*24*100, "/");
}

回答by ?siri L?km?l

as my testing,we can't use cookies in same time.if you set cookies. you need to reload page to grab those. put like this

作为我的测试,我们不能同时使用 cookie。如果您设置了 cookie。您需要重新加载页面才能获取这些页面。像这样放

if (!isset($_COOKIE['token'])) {
    setcookie("token", "value", time()+60*60*24*100, "/"); //this set cookies for first time
}

回答by silly

use

if(true === array_key_exists('secret', $_COOKIE) && strlen($_COOKIE['secret']) > 0) {
}