How to Validate an Email with PHP

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

A. Using the filter_var() Method

The first way to check if an email is well-formed is by using the filter_var() function.

In case the email is not well-formed, an error will be shown by the function, like here:

$myvar = ['hello',  42, [1, 'two'], 'apple'];

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

?>

B. Using the preg_match() Method

Another way of email validation is by using the preg_match() regular expression.

<?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. Two pieces of data are included in it: the variable, which should be checked, and the way of checking to apply.

Describing the preg_match() Regex

The preg_match() regular expression is aimed at searching the string for a pattern. True will be returned when the pattern is there, and, otherwise, false.