Nov 262012
 

If you are like me you get tired of constant email bounces from your web apps so I sat down and wrote this simple validator to save the mail server the extra load of having to deal with obvious typos.

// email Validator
// returns 1 on success 
// return -1 if the email is not in the correct format 
// return -2 if the email doesn't resolve 
function check_email($email) {   
        if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
                return (-1) ;
        }

        list($username, $domain) = explode('@', $email);

        //as per the RFC: check the domain for an MX record or A record and allow for IPv6 addresses
        if (!checkdnsrr($domain, 'MX') && !checkdnsrr($domain, 'A') && !checkdnsrr($domain, 'AAAA')) {
                return (-2) ;
        } 

        return (1) ;
}
Here is a quick example of how to call it:
$ret = check_email($h_email) ;

if ($ret > 0) {
        echo "valid email<br>" ;
} else {
        echo "error: " ;
        if($ret == -1 ){
                echo "invalid format<br>" ;
        }
        if($ret == -2 ) {
                echo "does not resolve<br>" ;
        }
}
 Posted by at 16:26

 Leave a Reply

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> <pre class="">

(required)

(required)