I have page1.php that uses a form to send the following data:
<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>
On page2.php, I do some basic validation so see that the form was actually submitted and that all data was entered:
<?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)");
}
?>
The problem is that the above feels very ugly and needs re-work when a new POST field is introduced in the page1.php form. How can I code this form validation better?
Store
f1,f2, etc. in an array and use a for statement to iterate through the array.Example:
Note: The above is untested.