我有 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/