How to check if an email address is valid in PHP

Sep 30, 2013, by admin

PHP has many awesome built in functions which can do amazing things. Here I am going to explain checkdnsrr() PHP function that will take an email address and performs a DNS lookup on the specified host (either a hostname or IP address). This is very cool function to check whether particular domain is exist or not. 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 is really amazing as you didn’t really need  to validate the email address in any other way, saving your time, server resources, and just making things really cool.

This function can look up the following record types:

bool checkdnsrr(host[, type]);

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: Check whether a given email address domain name has an MX resource record:

<?php
    $email = “support@bugtreat.com”;
    // Get host name from email address
    $host = explode(‘@’,$email);
    if(checkdnsrr ($host[1], ‘MX’)) {
    echo “It’s valid email address. MX record found for $email”;
    } else {
    echo “It’s invalid email address. MX record not exists for $email”;
    }
    ?>