PHP Email Validator – Email MX DNS Record Check
Validating an email address is one of the hardest feats on the web. A valid email can be marketing gold, but an invalid email address is dead weight. Not only does it require a CPU-taxing PHP regular expression ("/^[A-z0-9\._-]+"."@" . "[A-z0-9][A-z0-9-]*". "(\.[A-z0-9_-]+)*"."\.([A-z]{2,6})$/"), the regular expression can be useless even after it's validated for format if the domain doesn't exist. A regular expression simply wont do -- we need to think more low-level. What does email at any domain require? A DNS MX record. Well, PHP provides a great solution to validate that there's a MX record for the provided email address' domain.
The Code
function domain_exists($email,$record = 'MX'){
list($user,$domain) = split('@',$email);
return checkdnsrr($domain,$record);
}The Usage
if(domain_exists('user@davidwalsh.name')) {
echo('This MX records exists; I will accept this email as valid.');
}
else {
echo('No MX record exists; Invalid email.');
}You'll see that MX is the default record check, though you could change that to A if you want. This method is not bulletproof but the function does provide a compelling enough argument for an email existing or being a fraud. If a valid email address is important for your purposes, use this function. Try it for yourself!
Comments
Be Heard!
Share your thoughts without being a jerk! And wrap your code in <code> tags, f00!
Saved, for later use… :)
Thanks, Btw I like the way you display PHP code on your site.
Mark
This only checks if an email account can exist for the domain in question. For example I tested molly@frannleach.com and it came back valid. There is no email account of that name.
If my host is typical, all domains in an account will have the MX record set – which is why even domains I own with no email addresses attached have come back valid. Also most email addresses given by spammers are @gmail.com. This function, though it looks useful, has no validity as you will get false positives more often than false negatives.
@tiggsy: You’re correct but it at least prevents someone from using “user@adksjf8uwe4p8ujfasd.com”.
I have hunted around, and what you have given is the best that can be done, as one can’t rely on an email server being sufficiently insecure as to deny the existence of an email address. Many just swallow them without comment, but not all.
hi david
Is there anyway to check the user a/c also from that domain… and do u know how to login to webmail from website.I have done a form to collect user id and pass but its not passing to that webmail . if u have any reference or idea it woild be a great help for me
I know this is an old post but now that the “split” function has been deprecated. The following works.
function domain_exists( $email, $record = 'MX' ) {
list( $user, $domain ) = explode( '@', $email );
return checkdnsrr( $domain, $record );
}