MX Validation in PHP

Posted by Nessa | Posted in ,,,,, | Posted on December 1, 2007


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!

Comments (9)

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.

That needs another ) on the if statement *facepalm*

…and a semicolon =D

Yes, that too. I’m on a roll!

Well actually, no, you don’t put semicolons on if statements.

sure you do

at the end, that is

Using this still got flaw: you can type any username on valid domain (example: will pass the validation. Is there any other method of validating e-mail?

There’s this:

You can also try to create a custom function to perform a callout, but I’m honestly not sure how to do this.

Post a comment