$ _COOKIE ['cookiefoo'], try to get a cookie

I am new to webapps and PHP.

I am trying to get a cookie that it has not yet created, I mean, when I try to load a page that is looking for a non-existent cookie, I get an error message, I tried to get rid of this with an / catch attempt, but not success. This is the code I'm trying to do:

try{ $cookie = $_COOKIE['cookiefoo']; if($cookie){ //many stuffs here } else throw new Exception("there is not a cookie"); } catch(Exception $e){ } 

How can I achieve this, any ideas, this would be appreciated.

+6
php web-applications cookies
source share
1 answer

Use isset to prevent any warnings or notifications from occurring if the key does not exist:

 if(isset($_COOKIE['cookiefoo']) && !empty($_COOKIE['cookiefoo'])) { // exists, has a value $cookie = $_COOKIE['cookiefoo']; } 

The same thing can be done with array_key_exists , although I think isset more concise:

 if(array_key_exists('cookiefoo', $_COOKIE) && !empty($_COOKIE['cookiefoo'])) { // exists, has a value $cookie = $_COOKIE['cookiefoo']; } 
+7
source share

All Articles