PHP:检查任何已发布的变量是否为空 - 表单:所有字段都需要

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3190464/
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-25 08:57:47  来源:igfitidea点击:

PHP: check if any posted vars are empty - form: all fields required

phpformspostfield

提问by FFish

Is there a simpler function to something like this:

是否有一个更简单的功能是这样的:

if (isset($_POST['Submit'])) {
    if ($_POST['login'] == "" || $_POST['password'] == "" || $_POST['confirm'] == "" || $_POST['name'] == "" || $_POST['phone'] == "" || $_POST['email'] == "") {
        echo "error: all fields are required";
    } else {
        echo "proceed...";
    }
}

回答by Harold1983-

Something like this:

像这样的东西:

// Required field names
$required = array('login', 'password', 'confirm', 'name', 'phone', 'email');

// Loop over field names, make sure each one exists and is not empty
$error = false;
foreach($required as $field) {
  if (empty($_POST[$field])) {
    $error = true;
  }
}

if ($error) {
  echo "All fields are required.";
} else {
  echo "Proceed...";
}

回答by Jacob Relkin

emptyand issetshould do it.

empty并且isset应该这样做。

if(!isset($_POST['submit'])) exit();

$vars = array('login', 'password','confirm', 'name', 'email', 'phone');
$verified = TRUE;
foreach($vars as $v) {
   if(!isset($_POST[$v]) || empty($_POST[$v])) {
      $verified = FALSE;
   }
}
if(!$verified) {
  //error here...
  exit();
}
//process here...

回答by animuson

I use my own custom function...

我使用我自己的自定义函数...

public function areNull() {
    if (func_num_args() == 0) return false;
    $arguments = func_get_args();
    foreach ($arguments as $argument):
        if (is_null($argument)) return true;
    endforeach;
    return false;
}
$var = areNull("username", "password", "etc");

I'm sure it can easily be changed for you scenario. Basically it returns true if any of the values are NULL, so you could change it to empty or whatever.

我相信它可以很容易地为你的场景改变。基本上,如果任何值是 NULL,它就会返回 true,因此您可以将其更改为空或其他任何值。

回答by Nahser Bakht

if( isset( $_POST['login'] ) &&  strlen( $_POST['login'] ))
{
  // valid $_POST['login'] is set and its value is greater than zero
}
else
{
  //error either $_POST['login'] is not set or $_POST['login'] is empty form field
}

回答by Calin Rusu

I did it like this:

我是这样做的:

$missing = array();
 foreach ($_POST as $key => $value) { if ($value == "") { array_push($missing, $key);}}
 if (count($missing) > 0) {
  echo "Required fields found empty: ";
  foreach ($missing as $k => $v) { echo $v." ";}
  } else {
  unset($missing);
  // do your stuff here with the $_POST
  }

回答by user1518699

I just wrote a quick function to do this. I needed it to handle many forms so I made it so it will accept a string separated by ','.

我刚刚写了一个快速函数来做到这一点。我需要它来处理多种形式,所以我做了它,以便它接受以“,”分隔的字符串。

//function to make sure that all of the required fields of a post are sent. Returns True for error and False for NO error  
//accepts a string that is then parsed by "," into an array. The array is then checked for empty values.
function errorPOSTEmpty($stringOfFields) {
        $error = false;
            if(!empty($stringOfFields)) {
                // Required field names
                $required = explode(',',$stringOfFields);
                // Loop over field names
                foreach($required as $field) {
                  // Make sure each one exists and is not empty
                  if (empty($_POST[$field])) {
                    $error = true;
                    // No need to continue loop if 1 is found.
                    break;
                  }
                }
            }
    return $error;
}

So you can enter this function in your code, and handle errors on a per page basis.

所以你可以在你的代码中输入这个函数,并在每页的基础上处理错误。

$postError = errorPOSTEmpty('login,password,confirm,name,phone,email');

if ($postError === true) {
  ...error code...
} else {
  ...vars set goto POSTing code...
}

回答by bharadwaja Gummadi

Note : Just be careful if 0 is an acceptable value for a required field. As @Harold1983- mentioned, these are treated as empty in PHP. For these kind of things we should use issetinstead of empty.

注意:如果 0 是必填字段的可接受值,请小心。正如@Harold1983- 提到的,这些在PHP 中被视为空。对于这些事情,我们应该使用isset而不是empty

$requestArr =  $_POST['data']// Requested data 
$requiredFields = ['emailType', 'emailSubtype'];
$missigFields = $this->checkRequiredFields($requiredFields, $requestArr);

if ($missigFields) {
    $errorMsg = 'Following parmeters are mandatory: ' . $missigFields;
    return $errorMsg;
}

// Function  to check whether the required params is exists in the array or not.
private function checkRequiredFields($requiredFields, $requestArr) {
    $missigFields = [];
    // Loop over the required fields and check whether the value is exist or not in the request params.
    foreach ($requiredFields as $field) {`enter code here`
        if (empty($requestArr[$field])) {
            array_push($missigFields, $field);
        }
    }
    $missigFields = implode(', ', $missigFields);
    return $missigFields;
}

回答by d?lo sürücü

foreach($_POST as $key=>$value)
{

   if(empty(trim($value))
        echo "$key input required of value ";

}

回答by Doug Molineux

Personally I extract the POST array and then have if(!$login || !$password) then echo fill out the form :)

我个人提取 POST 数组,然后使用 if(!$login || !$password) then echo 填写表单:)