MX Validation in PHP

Hosting companies have all kinds of tactics to keep spam away from their customers, but one very common complaint I get is the amount of spam coming in through contact forms. Even though we don’t allow ‘nobody’ mail through the php mail() function and we provide the best server-side spam filters available, local mail cannot be filtered or limited. In other words, no spam filter in the world is going to save you from your shitty contact form.

I started recommending to our customers to implement MX checks in their forms as spam bots nowadays can easily get past things like captcha and textual confirmations. Spammers rarely send email from valid mail hosts so it’s very easy to filter these out with just a few lines of code:

list($user, $domain) = split(“@”, $email);
if (checkdnsrr($domain, “MX”)) {
} else {


To explain the code a little bit, you’re basically taking your stored email address variable ($email) and using the split() function to single out the domain name into one variable, $domain. When you pass the domain through the checkdnsrr() function, PHP will return either a ‘1’ or ‘0’ result, which is interpreted as either true or false. The above is just the basic code, but you can have it spit out errors as well:

if (checkdnsrr($domain, “MX”)) {
} else {
echo "Invalid email";

The checkdnsrr() function can also be used to check for other records as well, like A, CNAME, NS, etc.

Be Sociable, Share!

9 thoughts on “MX Validation in PHP

  1. You can also do this with checkmxrr() like so:

    if (checkmxrr($domain, $mx)
    } else {
    // Error reporting

    This also sticks a list of all MX records into the array $mx which you could probably use to check ips against with gethostbyname() if you were *really* paranoid. You could also use that in conjunction with GeoIP to block against certain Asian and European countries that are notorious for pumping out tons of spam.

Leave a Reply

Your email address will not be published. Required fields are marked *

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>