PHP: How to Validate an Email Address

In this tutorial you’ll learn how to validate an email address using PHP.

You’ll also find a complete PHP email validation example that you can copy & use right away.

Let’s get started.

PHP email validation


Contents:

PHP email validation with filter_var()

Let’s see how to validate an email address with PHP.

Let’s say that you have a PHP variable that should contain an email address:


$email = "name@mydomain.com";

To make sure that the $email variable contains a valid email address, you need the filter_var() function.

filter_var() is a PHP function that performs validation and sanitization checks on variables.

To tell filter_var() that you want to validate an email address, you need to use the FILTER_VALIDATE_EMAIL flag.

filter_var() returns true if the email is valid, false otherwise.

Here’s how to use it:

$email = 'name@mydomain.com';
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
   
   echo $email . ' is a valid email address.';
}
else {
   
   echo $email . ' is NOT a valid email address.';
}

name@mydomain.com is a valid email address.

filter_var() rejects email addresses that do not have a valid “name@domain” format, or that contain characters not allowed in an email address.

Here are some examples of valid and invalid addresses:

$emails = [
   'name@mydomain.com',  // Valid address
   'name_with_\'_quotes@mydomain.com',  // Valid: single quotes are allowed
   '@mydomain.com',  // Not valid: missing name
   'name@',  // Not valid: missing domain
   'name with spaces@mydomain.com',  // Not valid: spaces are not allowed
   'name_with_"_doublequotes@mydomain.com', // Not valid: double quotes are not allowed
   'name1@name2@mydomain.com' // Not valid: too many "@"
];
foreach ($emails as $email) {
   
   echo $email . ' --> ';
   
   if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
      
      echo 'valid.<br>';
   }
   else {
      
      echo 'NOT valid.<br>';
   }
}
name@mydomain.com --> valid.
name_with_'_quotes@mydomain.com --> valid.
@mydomain.com --> NOT valid.
name@ --> NOT valid.
name with spaces@mydomain.com --> NOT valid.
name_with_"_doublequotes@mydomain.com --> NOT valid.
name1@name2@mydomain.com --> NOT valid.

Validation VS Sanitization

filter_var() also supports the FILTER_SANITIZE_EMAIL flag.

If you use this flag, filter_var() sanitizes the string by removing all the characters that cannot be used in an email address.

However, this does not guarantee that the result is a valid email address.

Even if a string is free of invalid characters, it can still lack a proper email format.

Look at the following example:

$address = 'invalid_address_£()@';
echo 'Address: ' . $address . '<br>';
/* Sanitization removes all the invalid characters... */
$sanitizedAddress = filter_var($address, FILTER_SANITIZE_EMAIL);
echo 'Sanitized address: ' . $sanitizedAddress . '<br>';
/* However, the address is still invalid. */
if (filter_var($sanitizedAddress, FILTER_VALIDATE_EMAIL)) {
  
   echo 'The address is valid.';
}
else {
  
   echo 'The address is still not valid.';
}
Address: invalid_address_£()@
Sanitized address: invalid_address_@
The address is still not valid.

As you can see, using the FILTER_SANITIZE_EMAIL flag is not really useful because you still need to validate the variable.

I suggest you just use the FILTER_VALIDATE_EMAIL flag instead.

How to check the email’s domain

Let’s say that you have successfully validated your email address.

Now, how can you be sure that an email address actually exists?

The only way to know for sure is to try and send an email to that address and parse the SMTP server reply.

However, this procedure is complicated and it is not always reliable.

What you can do much more easily is to check the domain part of the email.

If the domain is valid, then you can assume the email is valid too.

First, you need to extract the domain from the address.

Here’s how:

$address = 'myaddress@gmail.com';
// Find the position of @
$atPos = mb_strpos($address, '@');
// Select the domain
$domain = mb_substr($address, $atPos + 1);

Next, validate the domain with the checkdnsrr() function.

You need to pass two arguments to this function.

The first argument is the domain followed by a dot. You need to add the dot to avoid false lookups.

The second argument is the “MX” string that tells the function to check for the email DNS record.

Here’s the code:

if (checkdnsrr($domain . '.', 'MX')) {
   
   echo 'Domain "' . $domain . '" is valid';
}
else {
   
   echo 'Domain "' . $domain . '" is not valid';
}

Domain "gmail.com" is valid

About front-end email validation

Front-end email validation is made directly in the browser.

For example, if you set the type of an HTML form input as “email”, the browser will automatically stop invalid email addresses from being submitted:


Email: <input type="email">

You can also use JavaScript to perform validation checks.

Front-end validation is handy to catch common user mistakes and to improve the user experience.

However, you must keep in mind that front-end validation is not secure and you must never rely on it.

Malicious users can easily bypass any kind of front-end validation and send invalid values to your PHP back-end script.

You always need to perform validation with PHP.

A complete example

Here’s a complete PHP email validation example that you can use as a reference for your own code.

Let’s begin with an HTML form that contains an email input field named “email”:

<form>
Your email: <input type="email" name="email">
<input type="submit" value="Submit">
</form>

And this is the PHP email validation code:

$email = NULL;
/* Read the "email" request variable. */
if (isset($_REQUEST['email'])) {
   
   $email = $_REQUEST['email'];
}
/* Validate the address. */
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
   
   echo $email . ' is NOT a valid email address.';
   die();
}
/* Check the domain. */
$atPos = mb_strpos($email, '@');
$domain = mb_substr($email, $atPos + 1);
if (!checkdnsrr($domain . '.', 'MX')) {
   
   echo 'Domain "' . $domain . '" is not valid';
   die();
}
/* The address is valid. */
echo $email . ' is a valid email address.';

Conclusion

Let’s recap what you learned:

  • You can validate an email address using filter_var() with the FILTER_VALIDATE_EMAIL flag.
  • If you use the FILTER_SANITIZE_EMAIL flag instead, filter_var() removes invalid characters from the string. But this does’t guarantee that the string contains a valid address.
  • You can check if a domain is valid with the checkdnsrr() function.
  • Front-end validation is never secure. PHP-based validation is always required.

Let me know if this tutorial has been helpful to you by leaving a comment below.

If you want to learn how to send emails with PHP, check my complete PHPMailer tutorial.

If you are interested in PHP security, consider enrolling in my professional PHP Security course.

Alex

Image by balasoiu on Freepik

Leave a Comment