PHP Form Complete
In this page:
if ($_SERVER["REQUEST_METHOD"] === "POST") {
$errors = [];
$value = htmlspecialchars(trim($_POST["field_name"])); // sanitize
if (empty($value)) {
$errors[] = "message"; // validate
}
if (empty($errors)) {
// process the data
}
}
Structuring a Complete Form Script
A complete form-handling script typically follows one pattern: check if the form was submitted (usually via $_SERVER["REQUEST_METHOD"]), if so validate and sanitize every field, collect any errors, and either show a success message or redisplay the form with errors and the previously entered values.
Example: Structuring a Complete Form Script
<?php
$_SERVER['REQUEST_METHOD'] = 'POST';
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$errors = [];
// validate and sanitize fields here
echo empty($errors) ? "Success" : "Redisplay with errors";
}
?>
Login to try C/C++/Java/PHP code in the editor
Validating Every Field
Each field gets its own validation rule appropriate to what it holds -- a name field checks it is not empty, an email field checks it looks like a valid address, a message field might check a minimum length -- and every failed check adds a clear, specific message to the errors array.
Example: Validating Every Field
<?php
// Declare `$name`, set to ""
$name = "";
// Declare `$email`, set to "not-an-email"
$email = "not-an-email";
// Declare `$errors` as an empty array
$errors = [];
if (empty($name)) $errors[] = "Name is required";
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) $errors[] = "Invalid email";
// Print a human-readable dump of `$errors`
print_r($errors);
?>
Login to try C/C++/Java/PHP code in the editor
Sanitizing Input Before Using It
Sanitizing means cleaning up a value so it is safe to use -- htmlspecialchars() prevents submitted text from being interpreted as HTML when displayed back on the page, and trim() removes accidental leading/trailing whitespace before validation and storage.
Example: Sanitizing Input Before Using It
<?php
// Declare `$comment`, set to " <script>bad</script> "
$comment = " <script>bad</script> ";
// Declare `$clean`, set to `htmlspecialchars(trim($comment))`
$clean = htmlspecialchars(trim($comment));
// Print `$clean` to the output
echo $clean;
?>
Login to try C/C++/Java/PHP code in the editor
Re-populating the Form After Errors
When validation fails, redisplaying the form with the user's already-typed values filled back in (using the value="" attribute) saves them from retyping everything -- only the fields that actually failed need correcting.
Example: Re-populating the Form After Errors
<?php
// Declare `$name`, set to "Alice"
$name = "Alice";
// Print '<input type="text" name="name" value="' . htmlspecialchars($name) . '">' to the output
echo '<input type="text" name="name" value="' . htmlspecialchars($name) . '">';
?>
Login to try C/C++/Java/PHP code in the editor
A Complete Contact Form Example
Putting everything together -- submission check, validation, sanitization, error display, and value re-population -- produces one complete, realistic contact-form script: it validates the name, email, and message; shows specific errors if any check fails; and confirms success only once every rule passes.
Example: A Complete Contact Form Example
<?php
// Declare `$name`, set to `trim($_POST['name'] ?? '')`
$name = trim($_POST['name'] ?? '');
// Declare `$email`, set to `trim($_POST['email'] ?? '')`
$email = trim($_POST['email'] ?? '');
// Declare `$message`, set to `trim($_POST['message'] ?? '')`
$message = trim($_POST['message'] ?? '');
// Declare `$errors` as an empty array
$errors = [];
if (empty($name)) $errors[] = "Name required";
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) $errors[] = "Valid email required";
if (strlen($message) < 10) $errors[] = "Message too short";
// Print `empty($errors) ? "Message sent!" : implode(", ", $errors)` to the output
echo empty($errors) ? "Message sent!" : implode(", ", $errors);
?>
Login to try C/C++/Java/PHP code in the editor
- Validating fields but forgetting to sanitize them too (or vice versa) -- validation checks correctness, sanitization cleans up potentially dangerous content, and a robust form needs both.
- Re-displaying a form after a failed validation without preserving the values the user already typed, forcing them to retype everything from scratch.
- Trusting that client-side (JavaScript) validation alone is enough, and skipping server-side validation entirely -- client-side checks can always be bypassed.
- A complete form-handling script combines: reading submitted data, validating each field, sanitizing values, collecting error messages, and conditionally showing success or the form again.
- Values should be re-populated back into the form on a failed submission, so the user does not have to retype everything.
- Both client-side and server-side validation have a role, but server-side validation is the one that cannot be bypassed and must never be skipped.
This end-to-end pattern uses only core PHP language features and works identically across every PHP-supporting server.
Chapter Quiz — Complete all 8 topics to unlock
0/8 topics done
Complete these topics first: