Checking if a $_COOKIE value is empty or not

2020-03-30 02:26发布

问题:

I assign a cookie to a variable:

$user_cookie = $_COOKIE["user"];

How can I check if the $user_cookie received some value or not?

Should I use if (empty($user_cookie)) or something else?

回答1:

Use isset() like so:

if (isset($_COOKIE["user"])){
$user_cookie = $_COOKIE["user"];
}

This tells you whether a key named user is present in $_COOKIE. The value itself could be "", 0, NULL etc. Depending on the context, some of these values (e.g. 0) could be valid.

PS: For the second part, I'd use === operator to check for false, NULL, 0, "", or may be (string) $user_cookie !== "".



回答2:

These are the things empty will return true for:

  • "" (empty string)
  • 0 (0 as an integer)
  • 0.0 (0 as float)
  • "0" (0 as string)
  • NULL
  • FALSE
  • array() (an empty array)
  • var $var; (a declared variable not in a class)

Taken straight from the php manual

So to answer your question, yes, empty() will be a perfectly acceptable function, and in this instance I'd prefer it over isset()



回答3:

If your cookie variable is an array:

if (!isset($_COOKIE['user']) || empty(unserialize($_COOKIE['user']))) {
    // cookie variable is not set or empty
}

If your cookie variable is not an array:

if (!isset($_COOKIE['user']) || empty($_COOKIE['user'])) {
    // cookie variable is not set or empty
}

I use this approach.



回答4:

Try empty function in php http://php.net/manual/en/function.empty.php

You can also use isset http://www.php.net/manual/en/function.isset.php



回答5:

isset(), however keep in mind, like empty() it cannot be used on expressions, only variables.

isset($_COOKIE['user']); // ok

isset($user_cookie = $_COOKIE['user']); // not ok

$user_cookie = $_COOKIE['user'];
isset($user_cookie); // ok

(isset() is the way to go, when dealing with cookies)



回答6:

You can use:

if (!empty($_COOKIE["user"])) {
   // code if not empty
}

but sometimes you want to set if the value is set in the first place

if (!isset($_COOKIE["user"])) {
   // code if the value is not set
}