Email validation via MX lookup in PHP

Josh Sherman
1 min read
Software Development PHP

Validating that an email addresses ain’t what it used to be. I remember writing simple regular expressions that worked out really well. These days there are a bajillion TLDs with more being added all of the time. Something I started doing is checking that the domain of the email being provided has the proper MX records. Without those DNS records, the domain can’t receive email, period.

Before we can look up the MX record, we will need to break apart the email address so we can isolate the domain:

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

Now that we have the domain extracted, we can check to see if any MX records exist:

if (checkdnsrr($domain, 'MX')) {
  // Domain has valid MX records
} else {
  // Domain is bad, don't accept this email!

Keep in mind that this method doesn’t guarantee that the email address is valid, it just guarantees that the domain itself can accept email. You will still want to include a few other sanity checks to ensure everything is good to go.

For me, the best way to guarantee that an email address is valid is to send them an email and make them click a validation link (I use Mandrill). Everything else is just a bonus so you can alert the user sooner than their address is bad.

Join the Conversation

Good stuff? Want more?

Weekly emails about technology, development, and sometimes sauerkraut.

100% Fresh, Grade A Content, Never Spam.

About Josh

Husband. Father. Pug dad. Musician. Founder of Holiday API, Head of Engineering and Emoji Specialist at Mailshake, and author of the best damn Lorem Ipsum Library for PHP.

Currently Reading

Parasie Eve

Previous Reads

Buy Me a Coffee Become a Sponsor

Related Articles