views:

46

answers:

1

Hi, I'm newbie with webapps and PHP.

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

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, it would be appreciated it.

+5  A: 

Use isset to prevent an any warnings or notices from happening if the key is non-existent:

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

The same can be done with array_key_exists, though I think isset is more concise:

if(array_key_exists('cookiefoo', $_COOKIE) && !empty($_COOKIE['cookiefoo'])) {
    // exists, has a value
    $cookie =  $_COOKIE['cookiefoo'];
}
karim79
If you look for non-empty value, condition like:if (!empty($_COOKIE['cookiefoo'])) is enough, no need for isset.
Piotr Pankowski
Either way, isset or empty does both really. I always use isset()
YouBook
+1 for isset, !empty will return false for values like an integer 0, an empty array, and an empty string. Isset will only return false for null and a variable that is not set.
Daniel