PHP 如果 (!isset(...) || !isset(...))

PHP If (!isset(...) || !isset(...))

我正在尝试检查是否存在第一个 $_COOKIE['one'] 或第二个 $_COOKIE['two'] 以及是否存在 none 以重定向用户。

当此脚本为 运行 时,这两个 cookie 中只有一个会存在。

if (!isset($_COOKIE['one']) || !isset($_COOKIE['two'])) {
    header('Location: ./');
} else {
    ...
}

我尝试了很多东西,但每次我遇到这个问题时,如果其中一个 cookie 总是存在的话。

如果只设置其中一个 cookie,那么您的 if 条件将始终为真,因此重定向将会发生。

|| 更改为 &&

if (!isset($_COOKIE['one']) && !isset($_COOKIE['two'])) {
  header('Location: ./');
} else {
  // 
}

这是一个简单的反逻辑案例。正如 Mark 指出的那样,您需要使用布尔 && (AND) 运算符。您正在尝试查看两者是否都不存在,然后发送 header。目前,如果其中一个存在,您仍然发送 header。

只需更改if (!isset($_COOKIE['one']) || !isset($_COOKIE['two'])) {

if (!isset($_COOKIE['one']) && !isset($_COOKIE['two'])) {

Or (||) returns 如果语句的左侧或右侧为真,则为真。并且 (&&) returns 仅当语句的两个部分都为真时才为真。 Not(!) 运算符反转 true->false 和 false->true。

isset 告诉您 cookie 是否存在。如果 cookie 存在,则 returns 为真。您在此使用 not 是正确的,因为您希望它告诉您 cookie 是否不存在(相反)。但是,如果两个 cookie 都不存在,您只想发送 header。或者,如果不存在,将发送它。

你写的逻辑与你真正想要的相反。

你说的


You're trying to check if

这是一个 if 条件。

the first $_COOKIE['one'] exists

为此你使用了 isset,你这样做是正确的。

OR the second $_COOKIE['two'] exists

因此您将使用 OR 运算符 ( || )

and if none exists to redirect the user.

那是一个else,然后用header重定向。


将您的文字转换为文字代码,您将得到:

if (isset($_COOKIE['one']) || isset($_COOKIE['two'])) {
    //... Do your thing
} else {
    header('Location: ./');
}

您的代码也适用于 Mark 在评论中提供的修复程序,但将来可能会使您感到困惑...

你也可以这样做来避免嵌套:

if (!(isset($_COOKIE['one']) || isset($_COOKIE['two']))) {
{
    header('Location: ./'); exit;
}

//... Do your thing

更优雅的是,isset() 可以处理多个参数并且取反它的 return 值将给你你想要的。

代码:(Demo)

var_export(!isset($cookie1, $cookie2));  // Are either missing? Yes, both are missing.
echo "\n";
$cookie1 = 'declared';
var_export(!isset($cookie1, $cookie2));  // Are either missing? Yes, one is missing.
echo "\n";
$cookie2 = 'declared';
var_export(!isset($cookie1, $cookie2));  // Are either missing? No, neither are missing.

输出:

true
true
false