How to validate email id using checkdnsrr() function in PHP

How to validate email id using checkdnsrr() function in PHP

Are you tired of dummy email id’s being used on your website. Like test@test.com, abc@abc.com etc ?

You can use PHP function

checkdnsrr()

It checks whether the dns value is valid or not. Only the email id with valid domain name will be accepted πŸ˜‰

This is inspired from the original post of one of our Author SNEHAL. Originally posted on his blog.

checkdnsrr() function will take an email address and performs a DNS lookup on the specified host (either a hostname or IP address). You can use this function before sending emails. The function will return an error informing the user that the domain related to email address probably doesn’t exist.

This function can look up the following record types:

bool checkdnsrr (string $host [, string $type = “MX” ] )

string $host: Hostname or IP address to check
string $type (optional): Type of record to check for

Record Type Details
________________________________________________________

A : Address: Defined in RFC 1035.
ALL : Any of the valid types.
CNAME : Canonical Name: Defined in RFC 1035.
MX : Mail Exchanger: Defined in RFC 1035.
NS : Name Server: Defined in RFC 1035.
PTR : Pointer: Defined in RFC 1035.
SOA : Start of Authority: Defined in RFC 1035.
________________________________________________________

Example :

<?php
$email = "test@gmail.com";
echo validate_email($email);

function validate_email($email){

$exp = "/^(([^()[]\.,;:s@”]+(.[^()[]\.,;:s@”]+)*)|(”.+”))@(([0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3})|(([a-zA-Z-0-9]+.)+[a-zA-Z]{2,}))$/”;

if(preg_match($exp,$email)){

if(checkdnsrr(array_pop(explode(“@”,$email)),”MX”)){
//array_pop : returns the last value of an array.
return “Valid Email”;
}else{
return “Invalid Email”;
}

}else{

return “Invalid ID”;

}
}

?>

Please provide your feedback and suggestions in comment section. To get latest Update follow our blog.

Leave a Comment