PHP Form Validation
Form validation is the process of checking that submitted data meets specific requirements before using it. Without validation, a script might process incomplete, malformed, or malicious data — causing errors, incorrect results, or security vulnerabilities. PHP handles validation on the server side, which is reliable and cannot be bypassed by disabling browser-side checks.
Why Validate on the Server Side
HTML and JavaScript can provide client-side validation for convenience, but server-side validation in PHP is mandatory for security. A user can disable browser checks, send requests with tools that bypass the browser entirely, or tamper with form data before it reaches the server. PHP validation catches all of these cases.
Sanitizing Input — htmlspecialchars()
Before displaying any user input in a web page, it must be sanitized to prevent Cross-Site Scripting (XSS) attacks. The htmlspecialchars() function converts special HTML characters to safe HTML entities.
<?php
$userInput = "<script>alert('hacked!')</script>";
$safeInput = htmlspecialchars($userInput);
echo $safeInput;
// Outputs: <script>alert('hacked!')</script>
// The browser displays the text, not executes the script
?>
Always apply htmlspecialchars() to any user-provided data before printing it into HTML.
Stripping Extra Spaces and Tags
<?php
$rawInput = " Hello World! ";
$cleaned = trim($rawInput); // Removes leading and trailing spaces
$noTags = strip_tags($rawInput); // Removes any HTML or PHP tags
echo $cleaned; // Outputs: Hello World!
echo $noTags; // Outputs: Hello World! (tags removed, spaces kept)
?>
Combining trim() and strip_tags() removes extra whitespace and prevents users from injecting HTML tags into plain text fields.
Checking for Required Fields
<?php
$name = "";
$errors = [];
if ($_SERVER["REQUEST_METHOD"] === "POST") {
$name = trim($_POST["name"]);
if (empty($name)) {
$errors[] = "Name is required.";
}
if (empty($errors)) {
echo "Welcome, " . htmlspecialchars($name) . "!";
} else {
foreach ($errors as $error) {
echo "<p>" . $error . "</p>";
}
}
}
?>
The empty() function returns true if the variable is an empty string, zero, null, or an empty array. It is the most reliable way to check for missing required input after applying trim().
Validating Email Addresses
PHP's filter_var() function with the FILTER_VALIDATE_EMAIL flag checks whether a string is a valid email format.
<?php
$email = "user@example.com";
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
echo "Invalid email address.";
} else {
echo "Email is valid.";
}
// More examples:
var_dump(filter_var("not-an-email", FILTER_VALIDATE_EMAIL)); // bool(false)
var_dump(filter_var("a@b.c", FILTER_VALIDATE_EMAIL)); // string(5) "a@b.c"
?>
Validating URLs
<?php
$url = "https://www.example.com";
if (!filter_var($url, FILTER_VALIDATE_URL)) {
echo "Invalid URL.";
} else {
echo "URL is valid.";
}
?>
Validating Numbers
<?php
$age = "25";
if (!is_numeric($age)) {
echo "Age must be a number.";
} elseif ((int)$age < 1 || (int)$age > 120) {
echo "Age must be between 1 and 120.";
} else {
echo "Valid age: " . (int)$age;
}
?>
Checking String Length
<?php
$password = "abc";
$minLength = 8;
$maxLength = 64;
if (strlen($password) < $minLength) {
echo "Password must be at least " . $minLength . " characters.";
} elseif (strlen($password) > $maxLength) {
echo "Password must not exceed " . $maxLength . " characters.";
} else {
echo "Password length is valid.";
}
?>
A Complete Validation Example
<?php
$name = $email = $website = "";
$errors = [];
if ($_SERVER["REQUEST_METHOD"] === "POST") {
// Name validation
$name = trim(htmlspecialchars($_POST["name"]));
if (empty($name)) {
$errors[] = "Name is required.";
} elseif (strlen($name) < 2) {
$errors[] = "Name must be at least 2 characters.";
}
// Email validation
$email = trim(htmlspecialchars($_POST["email"]));
if (empty($email)) {
$errors[] = "Email is required.";
} elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$errors[] = "Invalid email format.";
}
// Website validation (optional field)
$website = trim(htmlspecialchars($_POST["website"]));
if (!empty($website) && !filter_var($website, FILTER_VALIDATE_URL)) {
$errors[] = "Invalid website URL.";
}
// Process form only if no errors
if (empty($errors)) {
echo "<p>Form submitted successfully!</p>";
echo "<p>Name: " . $name . "</p>";
echo "<p>Email: " . $email . "</p>";
} else {
foreach ($errors as $error) {
echo "<p style='color:red;'>" . $error . "</p>";
}
}
}
?>
<form method="post" action="">
Name: <input type="text" name="name" value="<?= htmlspecialchars($name) ?>"><br>
Email: <input type="email" name="email" value="<?= htmlspecialchars($email) ?>"><br>
Website (optional): <input type="text" name="website" value="<?= htmlspecialchars($website) ?>"><br>
<input type="submit" value="Submit">
</form>
This pattern — collect data, validate, show errors or process — is the standard approach for PHP form handling. Notice that the form fields are repopulated with the previously entered values so the user does not lose their input when errors occur.
Key Points
- Server-side validation is mandatory — client-side checks can be bypassed.
htmlspecialchars()prevents XSS attacks by escaping HTML characters in output.trim()andstrip_tags()clean up input before validation.empty()checks for blank, zero, null, or missing values.filter_var()with appropriate flags validates emails, URLs, integers, and more.- Collect all errors into an array before deciding whether to process the form.
- Repopulate form fields with previously entered values when showing error messages.
