← Back to PHP Course | Chapter 10: Forms & Validation | Lesson 7 of 8

PHP Form Complete

Handling a form properly in PHP means pulling together several skills you have already learned individually -- reading submitted data, validating each field, sanitizing input against malicious content, and showing clear error messages -- into one complete, working script. This topic walks through a full, realistic contact-form example from start to finish.

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.

Note: Keep the overall structure the same across every form you build -- submitted check, validate, sanitize, branch on errors -- so the pattern becomes familiar and predictable.

Warning: Processing form data before confirming the request was actually a POST submission can cause errors on a plain page visit, where none of the expected fields exist yet.

Example: Structuring a Complete Form Script

php
<?php
$_SERVER['REQUEST_METHOD'] = 'POST';
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $errors = [];
    // validate and sanitize fields here
    echo empty($errors) ? "Success" : "Redisplay with errors";
}
?>

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.

Note: Write one specific error message per validation rule, rather than one generic "form has errors" message, so users know exactly what to fix.

Warning: Stopping validation at the first failed field (instead of checking all fields) forces users through a frustrating one-error-at-a-time correction cycle.

Example: Validating Every Field

php
<?php
$name = "";
$email = "not-an-email";
$errors = [];
if (empty($name)) $errors[] = "Name is required";
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) $errors[] = "Invalid email";
print_r($errors);
?>

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.

Note: Sanitize a value for its destination: htmlspecialchars() before echoing into HTML, and appropriate escaping/parameter binding before using a value in a database query.

Warning: Sanitizing a value does not replace validating it -- a sanitized-but-still-empty name field is still an invalid submission.

Example: Sanitizing Input Before Using It

php
<?php
$comment = "  <script>bad</script>  ";
$clean = htmlspecialchars(trim($comment));
echo $clean;
?>

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.

Note: Always run htmlspecialchars() on a value before placing it back into a value="" attribute, to avoid breaking the HTML if the submitted text happened to contain a quote character.

Warning: Forgetting to re-populate fields after a failed submission is one of the most common and most frustrating form-UX mistakes, forcing users to retype an entire form over a single typo.

Example: Re-populating the Form After Errors

php
<?php
$name = "Alice";
echo '<input type="text" name="name" value="' . htmlspecialchars($name) . '">';
?>

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.

Note: Use this same complete pattern as a template for any new form you build -- swap out the specific fields and validation rules for whatever that form actually needs.

Warning: Skipping server-side validation because client-side JavaScript already checks the fields leaves the form wide open to anyone submitting directly, bypassing the browser entirely.

Example: A Complete Contact Form Example

php
<?php
$name = trim($_POST['name'] ?? '');
$email = trim($_POST['email'] ?? '');
$message = trim($_POST['message'] ?? '');
$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";
echo empty($errors) ? "Message sent!" : implode(", ", $errors);
?>
Common Mistakes
  1. 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.
  2. Re-displaying a form after a failed validation without preserving the values the user already typed, forcing them to retype everything from scratch.
  3. Trusting that client-side (JavaScript) validation alone is enough, and skipping server-side validation entirely -- client-side checks can always be bypassed.
Chapter Summary
  • 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.
Browser Support

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:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.