简体   繁体   English

检查$ _COOKIE值是否为空

[英]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:

  • "" (empty string) “”(空字符串)
  • 0 (0 as an integer) 0(0为整数)
  • 0.0 (0 as float) 0.0(浮点数为0)
  • "0" (0 as string) “0”(0为字符串)
  • NULL 空值
  • FALSE
  • array() (an empty array) array()(一个空数组)
  • var $var; var $ var; (a declared variable not in a class) (不在类中的声明变量)

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. 值本身可以是""0NULL等。根据上下文,这些值中的一些(例如0 )可能是有效的。

PS: For the second part, I'd use === operator to check for false , NULL , 0 , "" , or may be (string) $user_cookie !== "" . PS:对于第二部分,我使用===运算符来检查falseNULL0"" ,或者可能是(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. 我用这种方法。

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM