检查$ _POST是否为空

时间:2016-09-13 04:13:53

标签: php post foreach

我意识到这个问题已被多次询问,但没有人为我解决了这个问题。

我想检查$ _POST数组中的任何值是否为空,除了两个(sHostFirstName和sHostLastName),如果有空值则抛出400错误。我可以让它抛出400错误的唯一方法是在header命令之后放置一个die()命令,但无论是否有空值我都会得到400错误。

foreach ($_POST as $key => $value) {
    if (empty($value) || !isset($value) && $key != 'sHostFirstName' || 'sHostLastName') {
        header("HTTP/1.1 400 Bad Request");
        break;
    }
}

3 个答案:

答案 0 :(得分:1)

如果变量已初始化,

isset()将返回true。如果您的表单字段的名称值设置为userName,那么在提交该表单时,该值将始终为“set”,尽管其中可能没有任何数据。

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

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

答案 1 :(得分:0)

像这样的东西

   //store and set default if not set - only needed for checkbox or radio buttons. for example, text fields are always submitted as an empty string.
   $sHostFirstName = isset($_POST['sHostFirstName']) ? $_POST['sHostFirstName'] : false;
  unset($_POST['sHostFirstName']); //remove so it's not part of our count
   //store and set default if not set - only needed for checkbox or radio buttons.
   $sHostLastName = isset($_POST['sHostLastName']) ? $_POST['sHostLastName'] : false;
   unset($_POST['sHostLastName']); //remove so it's not part of our count

   $post = array_filter(array_map('trim', $_POST)); //copy post remove empty items.
   if( count( $post ) != count($_POST) 
       //if count $_POST is not the same as count $post ( empty removed via array_filter) then something was removed / empty
       header('HTTP/1.1 400 Bad Request', true, 400);
       exit();
   }

应该在unset之后使用它们。见,

  • 将它们存储在变量中
  • 从帖子中删除
  • 然后从帖子
  • 中删除空
  • 计算副本( - 清空)并与原始数量进行比较
  • 如果计数不同则删除某些内容(即空)

无需循环。

您也可以为标题发送可选的第2和第3个参数:

http://php.net/manual/en/function.header.php

  

2nd = replace - 可选的replace参数指示标头是应该替换先前的类似标头,还是添加相同类型的第二个标头。默认情况下它将替换,但如果您传入FALSE作为第二个参数,则可以强制使用相同类型的多个标头。

     

3rd = http_response_code - 强制HTTP响应代码为指定值。请注意,如果字符串不为空,则此参数仅起作用。

答案 2 :(得分:0)

无需循环POST数据。将POST数据存储在变量$postData中,并删除键sHostFirstName和sHostLastName,因为不需要检查这两个键。

$postData包含需要检查空白条目的所有键值对。现在,使用array_filter()过滤掉所有空白条目,并将其存储在$filteredArray

最后,如果没有空白条目,$postData的长度将与``$ filteredArray`相同。如果长度不匹配,则意味着已经过滤了一个或多个数组键。

$postData = $_POST;
unset($postData['sHostFirstName'], $postData['sHostLastName']); // $postData contanis all key value pairs which can't be empty

$filteredArray = array_filter($postData); // Filters out the blank entries

/* If the length of `$filteredArray` and `$postData` aren't the same, that means one or more fields had been filtered out */

if (count($filteredArray) != count($postData)) {
    header("HTTP/1.1 400 Bad Request");
}