PHP Email Validate – Check Email MX DNS Record

Total Views : 1,280
Zoom In Zoom Out Read Later Print

A valid email address can be marketing gold, but an invalid email address is a dead weight for our list and waste of work. validating a simple structure is not enough if it not exists on the web. let's find out how you can do this to get a valid working email address from users.

An invalid email address not only does it require a CPU-taxing but other resources and time.  PHP regular expression like  ("/^[A-z0-9\._-]+"."@" . "[A-z0-9][A-z0-9-]*". "(\.[A-z0-9_-]+)*"."\.([A-z]{2,6})$/"), can validate a email address but it is useless even after it's validated for format if the domain doesn't exist. A regular expression simply won't do that, we need to check something else to validate email existence, and for this, to work we can check a DNS MX record of a domain name. we do not need to write any extra code to check MX record for an email address we can use the function provided by PHP itself.

1. Validating format of an email before checking MX record, use this one.

Valid Format

if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
  echo("Email is a valid email address");
} else {
  echo("Email is not a valid email address");

2.1 First, we will create a function to validate the MX record of the email.

domain_exists($email, $record)

function domain_exists($email, $record = 'MX') {
	list($user, $domain) = split('@', $email);
	return checkdnsrr($domain, $record);

2.2 Second Method if the first one failed.


function domain_exists($email){
	list($user, $domain) = explode('@', $email);
	$arr= dns_get_record($domain,DNS_MX);
			return $arr[0]['target'];

2. Using the function to check the email address.

Validate Email

if(domain_exists('')) {
	echo "This MX records exists; I will accept this email as valid.";
} else {
	echo "MX record dosen't texists;  Invalid email.";

Our function has MX as a default value for the record. We can change it for the other values like A record etc.  This method is not bulletproof or topmost but the function does provide enough data for an email existing or being a fraud. If a valid email address is important for your task to do, try this method.

See More

Latest Photos