How to Validate Email Addresses 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
// "[email protected]" looks like an email, so it passes even though its not real.
php > var_export(filter_var("[email protected]", FILTER_VALIDATE_EMAIL));
// "[email protected]" passes, gmail is a valid email server,
// but gmail require more than 3 letters for the address.
var_export(filter_var("[email protected]", FILTER_VALIDATE_EMAIL));

You could use it in your code like..

pattern_regex.php
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 requests. This will check via Real Email if the address is active.

validate_email.php
$email = "[email protected]";
$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");
}
// [email protected] is invalid because gmail require more than 3 letters for the address.
var_export(file_get_contents("https://isitarealemail.com/api/email/[email protected]"));
'{"status":"invalid"}'
// [email protected] is valid
var_export(file_get_contents("https://isitarealemail.com/api/email/[email protected]"));
'{"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.

validate_email_api_key.php
$email = "[email protected]";
$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.