Form Validation & Security
Never trust user input. Validate and clean data before using it.
What you will learn
- Check required fields
- Sanitize and validate input
- Prevent common attacks
Validate on the server
The browser’s validation can be bypassed, so PHP must always re-check. *Validation* means checking the data is acceptable (not empty, a real email). *Escaping* means making it safe to show. Use empty(), filter_var() and htmlspecialchars().
Good form handling follows the same safe order every time:
- Read each value from
$_POSTandtrim()off stray spaces. - Check required fields — make sure nothing important was left blank.
- Validate the format — e.g. confirm the email actually looks like an email.
- If anything fails, show a clear message and stop (do not use the bad data).
- Only once it all passes, use the data — and still escape it with
htmlspecialchars()before printing.
<?php
$name = trim($_POST["name"] ?? "");
$email = trim($_POST["email"] ?? "");
if ($name === "") {
echo "Name is required.";
} elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
echo "Please enter a valid email.";
} else {
// safe to use — escape before showing
echo "Welcome, " . htmlspecialchars($name);
}
?>Line by line: the first two lines read the fields and trim them (the ?? "" supplies an empty string if the field is missing, so PHP does not warn). The if checks the name is not blank. The elseif uses filter_var(..., FILTER_VALIDATE_EMAIL), which returns false for anything that is not a valid email — the ! flips that into "if NOT valid". Only the else branch, reached when every check passed, prints a welcome — and it wraps the name in htmlspecialchars() first.
Note: Output (for name "Asha" and email "asha@x.com"):
Welcome, Asha
If the name were blank you would instead see Name is required., and a bad email like "asha@" would give Please enter a valid email. — only one message ever shows, because the checks are an if/elseif/else chain.
Watch out: Always run user input through htmlspecialchars() before echoing it back — otherwise an attacker could inject <script> (an XSS attack). And for databases, use prepared statements (next unit) to prevent SQL injection.
Tip: The ?? (null coalescing) operator gives a default if a value is missing: $_POST["name"] ?? "" avoids “undefined index” warnings.
Q. Which function safely escapes user text before showing it on a page?
✍️ Practice
- Validate that a name is not empty and an email is valid.
- Escape user input with
htmlspecialcharsbefore echoing it.
🏠 Homework
- Add full validation and escaping to your earlier contact form.