Beginner-Friendly Topic
Take your time - it's perfectly normal to re-read this topic 2-3 times. Try the interactive code editor below to run code yourself. Use the Q&A section to check your understanding before moving on.You've got this!
Lesson 3 of 8
Form Handling - Validation, Sanitisation & PRG Pattern
Building a web form in PHP involves three responsibilities: rendering the form (GET), processing the submission (POST with validation), and redirecting on success (PRG pattern). The PRG (Post/Redirect/Get) pattern prevents duplicate form submissions when the user refreshes the success page.
Complete Form - Validate, Display Errors, PRG
<?php
declare(strict_types=1);
// contact.php - a complete contact form with PRG pattern
$errors = [];
$success = false;
$old = []; // repopulate form on error
if ($_SERVER["REQUEST_METHOD"] === "POST") {
$old = $_POST; // keep user input for repopulation
// ── Validate ──────────────────────────────────────────────
$name = trim($_POST["name"] ?? "");
$email = trim($_POST["email"] ?? "");
$message = trim($_POST["message"] ?? "");
if (empty($name) || mb_strlen($name) < 2) {
$errors["name"] = "Please enter your full name (at least 2 characters).";
}
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$errors["email"] = "Please enter a valid email address.";
}
if (mb_strlen($message) < 10) {
$errors["message"] = "Message must be at least 10 characters.";
}
if (mb_strlen($message) > 2000) {
$errors["message"] = "Message must be 2,000 characters or fewer.";
}
if (empty($errors)) {
// ── Sanitise before processing ────────────────────────
$safeName = htmlspecialchars($name, ENT_QUOTES, "UTF-8");
$safeEmail = htmlspecialchars($email, ENT_QUOTES, "UTF-8");
$safeMessage = htmlspecialchars($message, ENT_QUOTES, "UTF-8");
// Save to DB or send email here...
// mail($adminEmail, "New Contact: $safeName", $safeMessage);
// ── PRG: Redirect after successful POST ───────────────
// Prevents re-submission on browser refresh
header("Location: /contact?sent=1");
exit;
}
}
// Show success message from redirect
if (isset($_GET["sent"]) && $_GET["sent"] === "1") {
$success = true;
}
?>
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>Contact</title></head>
<body>
<?php if ($success): ?>
<p class="success">Your message was sent successfully!</p>
<?php endif; ?>
<form method="POST" action="/contact" novalidate>
<div>
<label for="name">Name</label>
<input type="text" id="name" name="name"
value="<?= htmlspecialchars($old["name"] ?? "", ENT_QUOTES, "UTF-8") ?>"
<?= isset($errors["name"]) ? 'aria-invalid="true"' : '' ?>>
<?php if (isset($errors["name"])): ?>
<span class="error"><?= htmlspecialchars($errors["name"]) ?></span>
<?php endif; ?>
</div>
<div>
<label for="email">Email</label>
<input type="email" id="email" name="email"
value="<?= htmlspecialchars($old["email"] ?? "", ENT_QUOTES, "UTF-8") ?>">
<?php if (isset($errors["email"])): ?>
<span class="error"><?= htmlspecialchars($errors["email"]) ?></span>
<?php endif; ?>
</div>
<div>
<label for="message">Message</label>
<textarea id="message" name="message" rows="6">
<?= htmlspecialchars($old["message"] ?? "", ENT_QUOTES, "UTF-8") ?>
</textarea>
<?php if (isset($errors["message"])): ?>
<span class="error"><?= htmlspecialchars($errors["message"]) ?></span>
<?php endif; ?>
</div>
<button type="submit">Send Message</button>
</form>
</body></html>Quick Quiz
Tip
Tip
Practice Form Handling Validation Sanitisation PRG Pattern in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.
Visual architecture and concepts for Form Handling - Validation, Sanitisation & PRG Pattern
Practice Task
Note
Practice Task - (1) Write a working example of Form Handling Validation Sanitisation PRG Pattern from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.
Common Mistake
Warning
A common mistake with Form Handling Validation Sanitisation PRG Pattern is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready php code.
Finished this lesson?