Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

PHP Email Validator - Email MX DNS Record Check

DZone's Guide to

PHP Email Validator - Email MX DNS Record Check

· Web Dev Zone ·
Free Resource

Jumpstart your Angular applications with Indigo.Design, a unified platform for visual design, UX prototyping, code generation, and app development.

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@domain.com'))
{
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!

Take a look at an Indigo.Design sample application to learn more about how apps are created with design to code software.

Topics:

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}