Reputation: 148
I set a cookie this way
$id = 5; //just for clarification
setcookie("NAME", $id, time()+3600*24);
And look for it this way
$cookie = $_COOKIE["NAME"];
I check if this cookie is set (using: if(isset($cookie)))
and it works perfectly.
The thing is, this code works only if the cookie is set, but if not, I get the following error
Notice: Undefined index: NAME in [path], line [line]
In some cases the cookie will not be set (naturally). Is there a way I can handle it?
Upvotes: 0
Views: 83
Reputation: 26699
$cookie = isset($_COOKIE["NAME"]) ? $_COOKIE["NAME"] : null;
and you can continue checking for isset($cookie)
whenever you use the cookie
Upvotes: 4
Reputation: 1970
You need to check isset($_COOKIE["NAME"])
or array_has_key($_COOKIE, "name");
or something like that
Upvotes: 1
Reputation: 1356
Yes, by checking isset($_COOKIE['NAME'])
before accessing it. Alternatively you can turn off that error message entirely (Not a good idea, it will be on by default on most servers usually). For that see the documentation. You would want to turn off E_NOTICE in this case.
Upvotes: 1
Reputation: 5524
Try using:
if (isset($_COOKIE['NAME'])){
echo "Cookie Is Set";
// Continue cookie validation without the echo.
}
Because you currently are referring to the global $_COOKIE
and not the individual key
Upvotes: 6