Checking if a $_COOKIE value is empty or not

2020-03-30 02:15发布

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?

6条回答
唯我独甜
2楼-- · 2020-03-30 02:32

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.

查看更多
狗以群分
3楼-- · 2020-03-30 02:32
闹够了就滚
4楼-- · 2020-03-30 02:37

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()

查看更多
5楼-- · 2020-03-30 02:38

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楼-- · 2020-03-30 02:40

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
}
查看更多
趁早两清
7楼-- · 2020-03-30 02:43

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 !== "".

查看更多
登录 后发表回答