在 PHP 中检查 COOKIE 时未定义的索引

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20205852/
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-25 02:58:53  来源:igfitidea点击:

Undefined index while checking for COOKIE in PHP

phpcookies

提问by Michael Samuel

I set a cookie on a visitor's PC to show a notice once every 24 hours. Recently I started getting the following error in my error log:

我在访问者的 PC 上设置了一个 cookie,每 24 小时显示一次通知。最近我开始在我的错误日志中收到以下错误:

PHP: undefined index notice in **

I use the following code to check if the cookie exists with value and if not show notice:

我使用以下代码来检查 cookie 是否存在并带有值,如果不显示通知:

if($_COOKIE['notice'] != 'yes')  
   echo 'notice';
}

I can use the following to avoid the PHP notice:

我可以使用以下方法来避免 PHP 通知:

if((isset($_COOKIE['notice']) || !isset($_COOKIE['notice'])) && $_COOKIE['notice'] != 'yes')

Is there a way to do this check in one step only like I was doing or in a similar way?

有没有一种方法可以像我一样或以类似的方式一步完成这项检查?

Thanks

谢谢

回答by ThW

The index 'notice' in your source does not match the reported index 'test' in the error message. To avoid notices, you validate a variable or an index before reading it. Here are two functions for the validation.

源中的索引“notice”与错误消息中报告的索引“test”不匹配。为避免通知,您在读取变量或索引之前对其进行验证。这里有两个用于验证的函数。

isset()

isset()

Is a positive check that the variable/index is set and not NULL

是对变量/索引已设置而不是 NULL 的肯定检查

if (isset($_COOKIE['notice']) && $_COOKIE['notice'] == 'yes') {
  // success
  echo 'Cookie equals "yes".';
}

You can use && (and) for a second condition, that has to be TRUE, too.

您可以将 && (and) 用于第二个条件,该条件也必须为 TRUE。

empty()

空的()

Is a negative check that the index/variable does not exists or has a value that is considered empty (NULL, 0, '', array()).

是对索引/变量不存在或具有被视为空的值(NULL、0、''、array())的否定检查。

if (empty($_COOKIE['notice']) || $_COOKIE['notice'] != 'yes') {
   // error
  echo 'Cookie does not exists, is empty or does not equal "yes".';
}

You can use || (or) to combine that with additional conditions that need to be FALSE, too.

您可以使用 || (或)将其与也需要为 FALSE 的其他条件相结合。

回答by Babblo

You always need to know if a variable is set before try to find what is inside, so yes.. you need to do the check. Also, your logic is wrong.. you are checking if noticeis or isn't set (allways true) and checking if noticeis "yes".

在尝试查找里面的内容之前,您总是需要知道是否设置了变量,所以是的..您需要进行检查。此外,您的逻辑是错误的..您正在检查是否notice设置(始终为真)并检查是否notice为“是”。

The code should be something like this:

代码应该是这样的:

if ( (!isset($_COOKIE['notice'])) || ( (isset($_COOKIE['notice'])) && ($_COOKIE['notice'] != 'yes') ) ) {
  //Show the notice
}