How to Validate Email Address in PHP

Check if an email address is correct and really exists using PHP


Email Validation in a Nutshell

An Email Address can look right but still be wrong and bounce. Real Email uses in depth email address validation to check if emails really exist without sending any messages.

Checking Formatting with filter_var

You can use Regular Expressions to check if an Email Address is formatted correctly. In PHP there is the built in regex, FILTER_VALIDATE_EMAIL

// "not an email" is invalid so its false.
php > var_export(filter_var("not an email", FILTER_VALIDATE_EMAIL));
false
// "foo@a.com" looks like an email, so it passes even though its not real.
php > var_export(filter_var("foo@a.com", FILTER_VALIDATE_EMAIL));
'foo@a.com'
// "foo@gmail.com" passes, gmail is a valid email server,
// but gmail require more than 3 letters for the address.
var_export(filter_var("foo@gmail.com", FILTER_VALIDATE_EMAIL));
'foo@gmail.com'

You could use it in your code like..

if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
// email matches the pattern
} else {
// email doesnt match the pattern
}

Real Email API Validation

To do full email validation inspecting the mail server you can use Real Email by making an API a request. This will check via Real Email if the address is active.

$email = "foo@bar.com";
$api_key = ???;

$result_json = file_get_contents("https://isitarealemail.com/api/email/validate?email=" . $email, false);

if (json_decode($result_json, true)['status'] == "valid") {
echo("email is valid");
} else if (json_decode($result_json, true)['status'] == "invalid") {
echo("email is invalid");
} else {
echo("email was unknown");
}
// foo@gmail.com is invalid because gmail require more than 3 letters for the address.
var_export(file_get_contents("https://isitarealemail.com/api/email/validate?email=foo@gmail.com"));
'{"status":"invalid"}'

// foobar@gmail.com is valid
var_export(file_get_contents("https://isitarealemail.com/api/email/validate?email=foobar@gmail.com"));
'{"status":"valid"}'

You will be able to test 100 emails per day for free. If you have more that that you will need to signup and get an API key. An Email Address might have the unknown status if the email server is unresponsive.

Email Validation Using an API Key

With an API key you wont be limited by how many addresses you can check or how fast you can check them.

$email = "foo@bar.com";
$api_key = ???;

$request_context = stream_context_create(array(
'http' => array(
'header' => "Authorization: Bearer " . $api_key
)
));

$result_json = file_get_contents("https://isitarealemail.com/api/email/validate?email=" . $email, false, $request_context);

if (json_decode($result_json, true)['status'] == "valid") {
echo("email is valid");
} else if (json_decode($result_json, true)['status'] == "invalid") {
echo("email is invalid");
} else {
echo("email was unknown");
}

Get started with Real Email validations today.