I assign a cookie to a variable:
$user_cookie = $_COOKIE[\"user\"];
How can I check if the $user_cookie received some value or
These are the things empty will return true for:
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()
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.
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 !== "".
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)
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
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
}