W3docs

How to Validate an Email with PHP

This tutorial explains how to validate an email using the PHP arsenal. Check out the examples of how to do that with the help of a PHP function and regex.

This tutorial shows the safest and simplest ways to validate an email with PHP.

A. Using the filter_var() Method

The recommended and simplest way to check if an email is well-formed is by using the <kbd class="highlighted">filter_var()</kbd> function.

If the email is not well-formed, the function returns false, as shown here:

php check email

<?php
$email = $_POST["email"];
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
  $emailErr = "Invalid email format";
}
?>

B. Using the preg_match() Method

Another way to validate an email is by using the <kbd class="highlighted">preg_match()</kbd> function with a regular expression.

php validate email

<?php

$email = "[email protected]";

if (preg_match("~([a-zA-Z0-9!#$%&'*+\-/=?^_`{|}~.]+)@([a-zA-Z0-9.-]+)\.([a-zA-Z0-9]{2,4})~", $email)) {
  echo 'This is a valid email.';
} else {
  echo 'This is an invalid email.';
}

?>

Describing the PHP filter_var() Function

This PHP function is aimed at validating and sanitizing data. It is capable of filtering a single variable with a particular filter. It accepts two main parameters: the variable to check and the filter to apply.

Describing the preg_match() Regex

The <kbd class="highlighted">preg_match()</kbd> function searches a string for a pattern. It returns true when the pattern is found, and false otherwise.