Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Undefined index while checking for COOKIE in PHP

Tags:

php

cookies

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

like image 614
Michael Samuel Avatar asked Nov 25 '13 23:11

Michael Samuel


2 Answers

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.

Or use the operator:

??

The operator assign a default value if the variable/index is not set or NULL:

$noticeCookie = (string)($_COOKIE['notice'] ?? 'no');
if ($noticeCookie === 'yes') {
  // success
  echo 'Cookie equals "yes".';

}
like image 168
ThW Avatar answered Oct 08 '22 01:10

ThW


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
}
like image 25
Babblo Avatar answered Oct 07 '22 23:10

Babblo