简体   繁体   中英

Undefined index while checking for COOKIE in PHP

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:

PHP: undefined index notice in **

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

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

I can use the following to avoid the PHP notice:

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

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.

isset()

Is a positive check that the variable/index is set and not 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.

empty()

Is a negative check that the index/variable does not exists or has a value that is considered empty (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.

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 notice is or isn't set (allways true) and checking if notice is "yes".

The code should be something like this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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