Never trust user input. It's the golden rule of web development. Users will submit empty fields, weird characters, malicious code, and things you never even imagined. Form validation is how you check that the data is actually what you expect before you use it.
Checking for Empty Inputs
The simplest validation is checking if a field is empty. Use empty() or compare against an empty string. For checkboxes and selects, use isset() to see if they were submitted at all.
<?php
if (empty($_POST["name"])) {
echo "Name is required";
}
if (!isset($_POST["agree"])) {
echo "You must agree to the terms";
}
?>
Try it Yourself โ
Validating Email and Number Fields
PHP has built-in validation for common types. Use filter_var() with FILTER_VALIDATE_EMAIL to check if an email looks real, and FILTER_VALIDATE_INT or FILTER_VALIDATE_FLOAT for numbers.
<?php
$email = "user@example.com";
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
echo "Valid email";
} else {
echo "Invalid email";
}
$age = 25;
if (filter_var($age, FILTER_VALIDATE_INT) && $age > 0) {
echo "Valid age";
}
?>
Try it Yourself โ
Sanitizing with htmlspecialchars
When you display user input back on a page, you need to escape it. If you don't, a user could inject JavaScript and steal other users' data โ that's a cross-site scripting (XSS) attack. htmlspecialchars() converts dangerous characters like < and > into safe HTML entities.
<?php
$unsafe = "<script>alert('hacked')</script>";
$safe = htmlspecialchars($unsafe);
echo $safe;
// Outputs: <script>...
?>
Try it Yourself โ