PHP Form Validation
Form validation ensures that data submitted by users meets certain requirements before your application processes it, such as checking that required fields are filled in and emails are properly formatted.
Validation should always happen on the server side (in PHP) even if you also validate on the client side with JavaScript, because client-side checks can be bypassed by disabling JavaScript or sending requests directly.
if (empty($_POST["name"])) { }
filter_var($email, FILTER_VALIDATE_EMAIL);Checking required fields
empty() checks whether a variable is empty or unset, which is useful for verifying that required form fields were actually filled in.
Validating formats
filter_var() with filters like FILTER_VALIDATE_EMAIL checks that a value matches an expected format, such as a valid email address.
<?php
$name = "";
if (empty($name)) {
echo "Name is required";
}
?>Name is requiredempty() detects that $name is an empty string and triggers the error message.
<?php
$email = "test@example.com";
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
echo "Valid email";
} else {
echo "Invalid email";
}
?>Valid emailfilter_var() with FILTER_VALIDATE_EMAIL confirms the string is a properly formatted email address.
Key points
- Server-side validation is essential and cannot be skipped even with client-side checks.
- empty() checks for missing or blank required fields.
- filter_var() validates formats like email addresses and URLs.
- Always show clear error messages when validation fails.
