PHP Form Complete
In this final section, we combine all the validation rules we have learned. This script ensures that all mandatory fields are filled, data is sanitized to prevent attacks, and formats like Email and URL are verified.
1. The Complete Validation Logic
This PHP code block handles the form submission, sanitizes input, and checks for specific data formats using preg_match() and filter_var().
<?php
// Define variables and set to empty values
$nameErr = $emailErr = $genderErr = $websiteErr = "";
$name = $email = $gender = $comment = $website = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
$nameErr = "Name is required";
} else {
$name = test_input($_POST["name"]);
if (!preg_match("/^[a-zA-Z-' ]*$/",$name)) {
$nameErr = "Only letters and white space allowed";
}
}
if (empty($_POST["email"])) {
$emailErr = "Email is required";
} else {
$email = test_input($_POST["email"]);
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email format";
}
}
if (empty($_POST["website"])) {
$website = "";
} else {
$website = test_input($_POST["website"]);
if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-9+&@#\/%=~_|]/i",$website)) {
$websiteErr = "Invalid URL";
}
}
if (empty($_POST["gender"])) {
$genderErr = "Gender is required";
} else {
$gender = test_input($_POST["gender"]);
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
2. The HTML Form with Sticky Data
The value attribute ensures the form is "sticky," meaning it retains the user's input even after an error is detected.
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Name: <input type="text" name="name" value="<?php echo $name;?>">
<span class="error">* <?php echo $nameErr;?></span><br>
E-mail: <input type="text" name="email" value="<?php echo $email;?>">
<span class="error">* <?php echo $emailErr;?></span><br>
Website: <input type="text" name="website" value="<?php echo $website;?>">
<span class="error"><?php echo $websiteErr;?></span><br>
Gender:
<input type="radio" name="gender" <?php if (isset($gender) && $gender=="female") echo "checked";?> value="female">Female
<input type="radio" name="gender" <?php if (isset($gender) && $gender=="male") echo "checked";?> value="male">Male
<span class="error">* <?php echo $genderErr;?></span><br>
<input type="submit" name="submit" value="Submit">
</form>
3. Displaying Results
Once all validations pass, you can process or display the collected data.
<?php
if($_SERVER["REQUEST_METHOD"] == "POST" && $nameErr == "" && $emailErr == "" && $websiteErr == "" && $genderErr == "") {
echo "<h2>Your Input:</h2>";
echo $name . "<br>" . $email . "<br>" . $website . "<br>" . $gender;
}
?>
Summary: By combining test_input(), empty(), and filter_var(), you have created a secure and user-friendly form that protects against common web vulnerabilities.