PHP:检查 POST 数据的正确方法?

标签 php html forms validation

我有 page1.php 使用表单发送以下数据:

<form action="page2.php" method="post">
<input type="text" name="f1">
<input type="text" name="f2">
<input type="text" name="f3">
<input type="text" name="f4">
<input type="submit" value="submit">
</form>

在 page2.php 上,我进行了一些基本验证,以查看表单是否已实际提交并且所有数据均已输入:

<?php
if($_SERVER['REQUEST_METHOD'] != "POST" || empty($_POST["f1"]) || empty($_POST["f2"]) || empty($_POST["f3"]) || empty($_POST["f4"]))
{
    $missing_input = array();

    if (empty($_POST["f1"]))
    {
        $missing_input[] = "field1";
    }
    if (empty($_POST["f2"]))
    {
        $missing_input[] = "field2";
    }
    if (empty($_POST["f3"]))
    {
        $missing_input[] = "field3";
    }
    if (empty($_POST["f4"]))
    {
        $missing_input[] = "field4";
    }

    die("Error: " . implode(", ", $missing_input)");
}
?>

问题是当在 page1.php 表单中引入一个新的 POST 字段时,上面的感觉非常丑陋并且需要重新工作。如何更好地编写此表单验证代码?

最佳答案

您可以使用一个简单的循环和一个包含字段名的变量:

<?php
if ($_SERVER['REQUEST_METHOD'] == "POST")
{
  $fieldnames = array(
    'f1' => 'field1',
    'f2' => 'field2'
    'f3' => 'field3'
    'f4' => 'field4'
  );
  $missing_input = $array();
  foreach ($fieldnames as $code => $label)
  {
    if (empty($_POST[$code]))
      {
          $missing_input[] = $label;
      }
  }

  //Display errors nicely
  if (count($missing_input) > 0):?>
  <p>The following fields are required :</p>
  <ul>
    <?php foreach ($missing_input as $field): ?>
    <li><?php echo $field ?></li>
    <?php endforeach; ?>
  </ul>
  <?php endif;
}

关于PHP:检查 POST 数据的正确方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7909104/

相关文章:

javascript - 让 Div 输入搜索值

java - 如何让顶级链接出现在 opencart 移动平台的标题中

php - 使用 PHP 更改查询的日期

php - 使用表单、PHP 和 MYSQL 提交、更新和删除

HTML 行为与 float 左侧菜单内联

Javascript/Html/Css 来自两个 javascript 数组的随机背景图像和 Word

php - 如何使表单发送简单的 HTML 电子邮件而不是纯文本

php - 有没有办法检查结果是表中的最后一个(最高 ID)?

php - 将用户的输入存储到数据库中

javascript - 我应该在 html 标记中添加 "javascript:"吗?