Undefined index: When converting cookie value to variable
The problem
The following code produces this error from the line "print $readerStatus" -
Undefined index: readerStatus
Code
<?php
//Get Cookie Value
if (isset($_COOKIE['readerStatus'])) {
$readerStatus=$_COOKIE['readerStatus'];
} Else {
$readerStatus="Not Set";}
echo "The value of Cookie readerStatus is " . $_COOKIE['readerStatus'];
print $readerStatus;
?>
Background The goal is simply that if a coo开发者_运维技巧kie is set I want to pass the value into a Javascript. My strategy is as follows:
- Get the value from the cookie
- Set a variable to the value of the cookie
- Then use a php echo inside of the Javascript to transfer the value.
It works as expected but Eclipse is giving me the error and so I assume there is something wrong with the above code.
I'd appreciate any pointers on possible sources of the problem.
Thanks
Is this working?
<?php
//Get Cookie Value
if (isset($_COOKIE['readerStatus'])) {
$readerStatus=$_COOKIE['readerStatus'];
} else {
$readerStatus="Not Set";
}
echo ("The value of Cookie readerStatus is ".$readerStatus);
print ($readerStatus);
?>
This is a warning, not an error. However, you can skip the error by using array_key_exists. Generally, I'm not a fan of isset for this kind of checking.
if (array_key_exists('readerStatus', $_COOKIE))
{
$readerStatus=$_COOKIE['readerStatus'];
}
else
{
$readerStatus='Not Set';
}
echo 'The value of Cookie readerStatus is '. $readerStatus;
Some IDEs are less forgiving than the PHP parser itself. That being said, do you get any errors or notices when running the code? Variables in PHP are implicitly declared, so the undefined index message is simply a NOTICE (that can be ignored) regarding the accessing of an array element without it existing first.
If you check it exists prior to accessing it like this, you shouldn't have a problem.
$readerStatus = isset($_COOIKE['readerStatus']) ? $_COOIKE['readerStatus'] : '';
精彩评论