Aaron
Aaron

Reputation: 11673

How would I test if a cookie is set using php and if it's not set do nothing

I've tried

 $cookie = $_COOKIE['cookie'];

if the cookie is not set it will give me an error

PHP ERROR
Undefined index: cookie

How would I prevent it from giving me an empty variable>

Upvotes: 21

Views: 61071

Answers (6)

Favour okechukwu
Favour okechukwu

Reputation: 77

This should help

$cookie = $_COOKIE['cookie']??'';

Its a shorter form of

if (isset($_COOKIE['cookie'])) {
     $cookie =$_COOKIE['cookie']; //cookie is set
  } else {
     $cookie = ""; //cookie not set
}

Then you can do

if(!empty($cookie)){
     // do something
  }

Upvotes: 1

Mike Q
Mike Q

Reputation: 7327

Example not mentioned in responses: Say you set a cookie for 60 seconds if conditions are right :

if ($some_condition == $met_condition) {
    setcookie('cookie', 'some_value', time()+ 60, "/","", false);
}

Technically we need to check that it's set AND it's not expired or it will throw warnings etc.. :

$cookie = ''; //or null if you prefer
if (array_key_exists('cookie', $_COOKIE) && isset($_COOKIE['cookie'])) {
    $cookie = $_COOKIE['cookie'];
}

You would want to check in a way that ensures that expired cookies aren't used and it's set, the above example could obviously not always set the cookie etc.. We should always account for that. The array_key_exists is mainly their to keep warnings from showing up in logs but it would work without it.

Upvotes: 0

Shoe
Shoe

Reputation: 76240

Depending on your needs.

// If not set, $cookie = NULL;
if (isset($_COOKIE['cookie'])) { $cookie = $_COOKIE['cookie']; }

or

// If not set, $cookie = '';
$cookie = (isset($_COOKIE['cookie'])) ? $_COOKIE['cookie'] : '';

or

// If not set, $cookie = false;
$cookie = (isset($_COOKIE['cookie'])) ? $_COOKIE['cookie'] : false;

References:

Upvotes: 6

gen_Eric
gen_Eric

Reputation: 227200

Use isset to see if the cookie exists.

if(isset($_COOKIE['cookie'])){
    $cookie = $_COOKIE['cookie'];
}
else{
    // Cookie is not set
}

Upvotes: 53

John Parker
John Parker

Reputation: 54425

You can use array_key_exists for this purpose as follows:

$cookie = array_key_exists('cookie', $_COOKIE) ? $_COOKIE['cookie'] : null;

Upvotes: 19

Naftali
Naftali

Reputation: 146302

Try this:

 $cookie = isset($_COOKIE['cookie'])?$_COOKIE['cookie']:'';
 //checks if there is a cookie, if not then an empty string

Upvotes: 4

Related Questions