【问题标题】:PHP: check if any posted vars are empty - form: all fields requiredPHP:检查任何已发布的变量是否为空 - 表单:所有字段都是必需的
【发布时间】:2011-03-12 13:16:14
【问题描述】:

有没有更简单的函数来做这样的事情:

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...";
    }
}

【问题讨论】:

    标签: php forms post field


    【解决方案1】:

    类似这样的:

    // 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...";
    }
    

    【讨论】:

    • 再次,我推荐一个 isSet($_POST[$field])。不过,这是一个很好的解决方案。
    • empty() 检查是否存在和非假值(null、false、0、空字符串)。
    • 这个foreach 只会验证array(即电子邮件)的最后一个值,因为它会覆盖之前的$error 验证。
    • @NimitzE。不必要。 $error 设置为 false,只有当字段为空时才会更改。哪个字段抛出它并不重要,因为一旦它被抛出,它就会被抛出。即如果name 为空,它将运行false, false, false, true, false, false,但由于if 中没有else$error 现在是true
    • 如果 0 是必填字段的可接受值,请小心。正如@Harold1983-所提到的,这些在 PHP 中被视为空。最好使用isset
    【解决方案2】:

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

    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");
    

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

    【讨论】:

      【解决方案3】:
      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
      }
      

      【讨论】:

      • 如果您提交了一个空字段,那么 strlen() 的计算结果为 0,这在 PHP 中为 false。
      • 如果0 值有意义,这是更好的答案
      【解决方案4】:

      emptyisset 应该这样做。

      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...
      

      【讨论】:

      • 我认为您还需要一个 isSet - 否则如果根本没有发布该值,您将收到错误消息。
      • empty() 完成了整个工作,无需调用isset() 这是多余的逻辑。
      【解决方案5】:

      我是这样做的:

      $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
        }
      

      【讨论】:

        【解决方案6】:

        我刚刚编写了一个快速函数来执行此操作。我需要它来处理许多表格,所以我做了它,所以它可以接受一个由','分隔的字符串。

        //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;
        }
        

        因此,您可以在代码中输入此函数,并按页面处理错误。

        $postError = errorPOSTEmpty('login,password,confirm,name,phone,email');
        
        if ($postError === true) {
          ...error code...
        } else {
          ...vars set goto POSTing code...
        }
        

        【讨论】:

          【解决方案7】:

          注意:如果 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;
          }
          

          【讨论】:

            【解决方案8】:
            foreach($_POST as $key=>$value)
            {
            
               if(empty(trim($value))
                    echo "$key input required of value ";
            
            }
            
            

            【讨论】:

            • 我不明白这如何回答这个问题?
            • 如果为空任何 $_POST 键处理它并给出消息
            • 具体处理什么?您正在检查随机值。问题是关于验证强制性输入。
            • @Dharman 问题是关于填写 all 字段,所以我看不出这个解决方案应该是完全错误的
            • POST 为空怎么办?如果我不提交任何数据怎么办?您的验证将接受它,因为不会执行 foreach 循环。
            【解决方案9】:

            我个人提取 POST 数组,然后让 if(!$login || !$password) 然后回显填写表单:)

            【讨论】:

            • Awww,总是一种危险的做法,因为有可能通过$_POST 将全局变量偷运到您的脚本中。
            • 我以前听说过一些关于这个的事情,它可能不是最好的方法:) 特别是如果它很重要
            猜你喜欢
            • 2012-06-21
            • 1970-01-01
            • 1970-01-01
            • 2013-09-05
            • 2021-05-12
            • 2012-12-29
            • 2012-02-21
            • 1970-01-01
            • 2014-04-28
            相关资源
            最近更新 更多