php 检查 $_POST-value 是否为空

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9154719/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 06:17:11  来源:igfitidea点击:

Check whether $_POST-value is empty

phpif-statementstring

提问by Spencer McCreary

if(isset($_POST['submit'])) {
    if(!isset($_POST['userName'])) {
        $username = 'Anonymous';
    }      
    else $username = $_POST['userName'];
}

I cannot get the $usernameto be "Anonymous"? It is either blank or the value of $_POST['userName'].

我不能$username成为“匿名者”?它要么是空白,要么是 的值 $_POST['userName']

回答by Michael Berkowski

If the form was successfully submitted, $_POST['userName']should always be set, though it may contain an empty string, which is different from not being set at all. Instead check if it is empty()

如果表单提交成功,$_POST['userName']应该总是设置,尽管它可能包含一个空字符串,这与根本没有设置不同。而是检查它是否是empty()

if (isset($_POST['submit'])) {
    if (empty($_POST['userName'])) {
        $username = 'Anonymous';
    } else { 
        $username = $_POST['userName'];
    }
}

回答by Andy

isset()will return true if the variable has been initialised. If you have a form field with its namevalue set to userName, when that form is submitted the value will always be "set", although there may not be any data in it.

isset()如果变量已初始化,则返回 true。如果您的表单字段的name值设置为userName,则提交该表单时,该值将始终为“设置”,尽管其中可能没有任何数据。

Instead, trim()the string and test its length

相反,trim()字符串并测试其长度

if("" == trim($_POST['userName'])){
    $username = 'Anonymous';
}      

回答by Gajus

To check if the property is present, irrespective of the value, use:

要检查属性是否存在,无论值如何,请使用:

if (array_key_exists('userName', $_POST)) {}

To check if the property is set (property is present and value is not nullor false), use:

要检查属性是否已设置(属性存在但值不存在nullfalse),请使用:

if (isset($_POST['userName'])) {}

To check if the property is set and not empty (not an empty string, 0(integer), 0.0(float), '0'(string), null, falseor [](empty array)), use:

要检查属性是否已设置且不为空(不是空字符串、0(整数)、0.0(浮点数)、'0'(字符串)nullfalse[](空数组)),请使用:

if (!empty($_POST['userName'])) {}

回答by Anthony Rutledge

Question:Check whether a $_POST value is empty.

问题:检查 $_POST 值是否为

Translation:Check to see if an array key/index has a value associated with it.

翻译:检查数组键/索引是否具有与其关联的值。

Answer: Depends on your emphasis on security. Depends on what is allowed as valid input.

答:取决于您对安全的重视程度。取决于允许作为有效输入的内容。

1. Some people say use empty().

From the PHP Manual: "[Empty] determines whether a variable is considered to be empty. A variable is considered empty if it does not exist or if its value equals FALSE." The following are thus considered empty.

来自 PHP 手册:“[Empty] 确定变量是否被视为空。如果变量不存在或其值等于 FALSE,则将其视为空。” 因此,以下内容被认为是空的。

"" (an empty string)
0 (0 as an integer)
0.0 (0 as a float)
"0" (0 as a string)
NULL
FALSE
array() (an empty array)
$var; (a variable declared, but without a value)

If none of these values are valid for your input control, then empty()would work. The problem here is that empty()might be too broadto be used consistently (the same way, for the same reason, on different input control submissions to $_POSTor $_GET). A good use of empty()is to check if an entire arrayis empty (has no elements).

如果这些值都不适用于您的输入控件,则empty()可以使用。这里的问题是它empty()可能太广泛而无法一致使用(同样的方式,出于同样的原因,在不同的输入控件提交给$_POST$_GET)。一个很好的用途empty()是检查整个数组是否为空(没有元素)。

2. Some people say use isset().

isset()(a language construct) cannot operate on entire arrays, as in isset($myArray). It can only operate on variablesand array elements(via the index/key): isset($var)and isset($_POST['username']). The isset()language construct does two things. First it checks to see if a variable or array index/key has a value associated with it. Second, it checks to make sure that value is not equal to the PHP NULL value.

isset()(语言构造)不能对整个数组进行操作,如isset($myArray). 它只能对变量数组元素进行操作(通过索引/键):isset($var)isset($_POST['username'])。在isset()语言结构做了两两件事。首先,它检查变量或数组索引/键是否具有与其关联的值。其次,它会检查以确保该值不等于 PHP NULL 值。

In short, the most accurate check can be accomplished best with isset(), as some input controls do not even register with $_POST when they are not selected or checked. I have never known a form that submitted the PHP NULL value. None of mine do, so I use isset()to check if a $_POSTkey has no value associated with it (and that is not NULL). isset()is a much stricter testof emptiness (in the sense of your question) than empty().

简而言之,使用 可以最好地完成最准确的检查isset(),因为某些输入控件在未选中或未选中时甚至不会使用 $_POST 进行注册。我从来不知道提交 PHP NULL 值的表单。我的都没有,所以我isset()用来检查一个$_POST键是否没有与之关联的值(并且不是 NULL)。isset()是一种更严格的测试空虚的(在你的问题的意义上)比empty()

3. Some people say just do if($var), if($myArray), or if($myArray['userName']) to determine emptiness.

You can test anything that evaluates to trueor falsein an if statement. Empty arrays evaluate to false and so do variables that are not set. Variables that contain the PHP NULL value also evaluate to false. Unfortunately in this case, like with empty(), many more things also evaluate to false: 1. the empty string '', zero (0), zero.zero (0.0), the string zero '0', boolean false, and certain empty XML objects.

--Doyle, Beginning PHP 5.3

您可以在 if 语句中测试任何计算结果为truefalse的内容。空数组的计算结果为 false,未设置的变量也是如此。包含 PHP NULL 值的变量也计算为 false。不幸的是,在这种情况下,像 with 一样empty(),还有更多的东西也会被评估为 false:1. 空字符串 ''、零 (0)、zero.zero (0.0)、字符串零 '0'、布尔值 false 和某些空的 XML对象。

--Doyle,从 PHP 5.3 开始

In conclusion, use isset()and consider combining it with other tests. Example:

总之,使用isset()并考虑将其与其他测试结合使用。例子:

May not work due to superglobal screwiness, but would work for other arrays without question.

由于超全局扭曲,可能无法正常工作,但毫无疑问适用于其他阵列。

if (is_array($_POST) && !empty($_POST)) {
    // Now test for your successful controls in $_POST with isset()
} 

Hence, why look for a value associated with a key before you even know for sure that $_POSTrepresents an array and has any values stored in it at all (something many people fail to consider)? Remember, people can send data to your form without using a web browser. You may one day get to the point of testing that $_POSTonly has the allowed keys, but that conversation is for another day.

因此,为什么要在您确定$_POST表示一个数组并在其中存储任何值之前查找与键关联的值(许多人没有考虑到这一点)?请记住,人们可以在不使用 Web 浏览器的情况下向您的表单发送数据。您可能有一天会到达$_POST只有允许的密钥的测试点,但该对话将在另一天进行。

Useful reference:

有用的参考:

PHP Manual: Type Testing Comparison Tables

PHP 手册:类型测试比较表

回答by Dan Kanze

Change this:

改变这个:

if(isset($_POST['submit'])){

    if(!(isset($_POST['userName']))){
    $username = 'Anonymous';
    }      
    else $username = $_POST['userName'];
}

To this:

对此:

if(!empty($_POST['userName'])){
     $username = $_POST['userName'];
}

if(empty($_POST['userName'])){
     $username = 'Anonymous';
}

回答by Tschallacka

i'd use a simple one line comparisant for these use cases

对于这些用例,我会使用简单的一行比较

$username = trim($_POST['userName'])?:'Anonymous';

This is for the use case you are certain error logging is off so you don't get a warning that the variable isn't initialised.

这是针对您确定错误日志记录已关闭的用例,因此您不会收到变量未初始化的警告。

this is the paranoid version:

这是偏执版本:

$username = !empty(trim(isset($_POST['userName'])?$_POST['userName']:''))?$_POST['userName']:'Anonymous';

This implements a check if the $_POSTvariable is set. before accessing it.

这会检查是否$_POST设置了变量。在访问它之前。

回答by Amazing B

$username = filter_input(INPUT_POST, 'userName', FILTER_SANITIZE_STRING);
if ($username == '') {$username = 'Anonymous';}

Best practice - always filter inputs, sanitize string is ok, but you're better off using a custom callback function to really filter out what's not acceptable. Then check the now-safe variable if it is null/empty and if it is, set to Anonymous. Does not require 'else' statement as it was set if it existed on the first line.

最佳实践 - 始终过滤输入,清理字符串是可以的,但最好使用自定义回调函数来真正过滤掉不可接受的内容。然后检查现在安全的变量是否为空/空,如果是,则设置为匿名。不需要 'else' 语句,因为如果它存在于第一行,则已设置。

回答by GoldenNewby

isset is testing whether or not the key you are checking in the hash (or associative array) is "set". Set in this context just means if it knows the value. Nothing is a value. So it is defined as being an empty string.

isset 正在测试您在散列(或关联数组)中检查的键是否为“设置”。在此上下文中设置仅意味着它是否知道该值。没有什么是价值。所以它被定义为一个空字符串。

For that reason, as long as you have an input field named userName, regardless of if they fill it in, this will be true. What you really want to do is check if the userName is equal to an empty string ''

因此,只要您有一个名为 userName 的输入字段,无论他们是否填写,这都是正确的。您真正想要做的是检查 userName 是否等于空字符串 ''