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.
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.
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".';
}
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With