Validate Email in PHP Using filter_var
This article demonstrates how to validate an email address in PHP
using the native filter_var() function. You will learn the
syntax, see practical code examples, and understand how this built-in
filter simplifies email verification without the need for complex
regular expressions.
In PHP, the most efficient and secure way to validate an email
address is by using the filter_var() function combined with
the FILTER_VALIDATE_EMAIL filter. This built-in solution
checks if the email address conforms to the official RFC 822 e-mail
address specifications.
The Syntax
The filter_var() function takes the variable you want to
check as the first argument, and the filter type as the second
argument:
filter_var($email, FILTER_VALIDATE_EMAIL)This function returns the filtered data (the email string itself) if
it is valid, or false if the email is invalid.
Code Example
Here is a simple PHP script showing how to implement this validation:
<?php
// Define the email address to validate
$email = "user@example.com";
// Validate the email
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
echo "The email address '$email' is valid.";
} else {
echo "The email address '$email' is invalid.";
}
?>Sanitizing Before Validating
In some cases, input data may contain accidental spaces or illegal
characters. To handle this, you can sanitize the email first using
FILTER_SANITIZE_EMAIL before performing the validation
check:
<?php
$raw_email = " user@example.com ";
// Remove illegal characters and whitespace
$clean_email = filter_var($raw_email, FILTER_SANITIZE_EMAIL);
// Validate the sanitized email
if (filter_var($clean_email, FILTER_VALIDATE_EMAIL)) {
echo "The email address is valid.";
} else {
echo "The email address is invalid.";
}
?>Key Considerations
While FILTER_VALIDATE_EMAIL ensures the string is
formatted correctly as an email address, it does not verify that the
domain name actually exists, that the mail server is active, or that the
specific inbox exists. It only validates the syntax of the string.