Checking if a $_COOKIE value is empty or not

后端 未结 6 1933
盖世英雄少女心
盖世英雄少女心 2021-01-15 12:27

I assign a cookie to a variable:

$user_cookie = $_COOKIE[\"user\"];

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

相关标签:
6条回答
  • 2021-01-15 13:08

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

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2021-01-15 13:14

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

    0 讨论(0)
  • 2021-01-15 13:17

    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)

    0 讨论(0)
  • 2021-01-15 13:20

    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

    0 讨论(0)
  • 2021-01-15 13:21

    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
    }
    
    0 讨论(0)
提交回复
热议问题