[英]Checking if a $_COOKIE value is empty or not
I assign a cookie to a variable: 我为变量分配了一个cookie:
$user_cookie = $_COOKIE["user"];
How can I check if the $user_cookie
received some value or not? 如何检查
$user_cookie
收到了某些值?
Should I use if (empty($user_cookie))
or something else? 我应该使用
if (empty($user_cookie))
还是别的什么?
These are the things empty will return true for: 这些是空的东西将返回true:
Taken straight from the php manual 直接从PHP手册
So to answer your question, yes, empty()
will be a perfectly acceptable function, and in this instance I'd prefer it over isset()
所以回答你的问题,是的,
empty()
将是一个完全可以接受的函数,在这个例子中我更喜欢它而不是isset()
Use isset() like so: 像这样使用isset() :
if (isset($_COOKIE["user"])){
$user_cookie = $_COOKIE["user"];
}
This tells you whether a key named user
is present in $_COOKIE
. 这会告诉您
$_COOKIE
是否存在名为user
的键。 The value itself could be ""
, 0
, NULL
etc. Depending on the context, some of these values (eg 0
) could be valid. 值本身可以是
""
, 0
, NULL
等。根据上下文,这些值中的一些(例如0
)可能是有效的。
PS: For the second part, I'd use ===
operator to check for false
, NULL
, 0
, ""
, or may be (string) $user_cookie !== ""
. PS:对于第二部分,我使用
===
运算符来检查false
, NULL
, 0
, ""
,或者可能是(string) $user_cookie !== ""
。
If your cookie variable is an array : 如果您的cookie变量是一个数组 :
if (!isset($_COOKIE['user']) || empty(unserialize($_COOKIE['user']))) {
// cookie variable is not set or empty
}
If your cookie variable is not an array : 如果您的cookie变量不是 数组 :
if (!isset($_COOKIE['user']) || empty($_COOKIE['user'])) {
// cookie variable is not set or empty
}
I use this approach. 我用这种方法。
Try empty function in php http://php.net/manual/en/function.empty.php 在php http://php.net/manual/en/function.empty.php中尝试空函数
You can also use isset http://www.php.net/manual/en/function.isset.php 您也可以使用isset http://www.php.net/manual/en/function.isset.php
isset()
, however keep in mind, like empty()
it cannot be used on expressions, only variables. isset()
,但请记住,像empty()
它不能用于表达式,只能用于变量。
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 ) (
isset()
是处理cookie时的方法 )
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
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.