RSS
 

Check if email domain exists with PHP

04 Oct

Imagine this situation: Someone contacts your client but misspells the email and your client doesn’t have a clue what’s wrong with the email, all your client knows is that when an email is sent to that address they get an error message back. The result is the loss of a possible client and a client that will think the company it’s not interested.

PHP has a function called checkdnsrr that checks DNS records to a certain given host name or IP address making possible to check is a domain really exists or there is something wrong with it. This is good to check is the email is spam.

So let’s create a function to allow you to check the dns record of a full email address:

function VerifyEmailAddress($email) {
    list($user, $domain) = explode("@", $email);
    $result = checkdnsrr($domain, 'MX');
    return($result);
}

This function breaks the email string example@domain.tld giving the username the the content before @ and the domain the content after the @.
If you insert an email like example@domain.tld the user would be example and the domain would be domain.tld.

After breaking the email into user and domain the function calls checkdnsrr to check is the MX records on the $domain variable returning 1 is the domain exists or 0 if the domain does not exist.

Now you need to call it when checking an email:

if(VerifyEmailAddress($email) != 1) {
    echo "The e-mail you inserted is not valid.";
}

And here you have it. You can now check if the domain of an email exists.
For complete email verification I advise you to implement the following functions:

  • Check if email string inserted is a correct email for. Must have string@string.com
  • Check if the email domain exists. You can use this tutorial for that
  • Limit the amount of tries, for a determined period of time, a user can insert an email in order to stop possible spam bots
 
 

Tags:

Leave a Reply

 
 
 

Page optimized by WP Minify WordPress Plugin