Ultimate PHP Email validation

Below you will find what we call the Ultimate PHP Email validation function for validating emails. 

The Ultimate PHP Email validation function checks the email syntax, the user name if it has the "@" sign, the domain part and the TLD extension(you might need to update those and add any new ones that were added in the mean time). The different thing about this function, is that it checks if the domain name is valid by checking if it has MX records(Mail exchange server). This check will eliminate typing errors, intentional invalid emails and mostly make your life easier :-).

Though this does not check the username for the specific mail account whether it exists on the mail server. SMTP check is to come in the next version.

Code: function test_email_with_mx(&$themail){
$themail = mb_strtolower($themail);
if (mb_ereg_match ("^[a-z0-9._-]+@[a-z0-9.-]+.(?:[a-zA-Z]{2}|aero|asia|biz|com|coop|edu|gov|info|int|jobs|mil|mobi|museum|name|net|org|pro|tel|travel|xxx)$", $themail )) {
$emailParts = explode("@", $themail);
if (count($emailParts) === 2) {
$theDomain = $emailParts[1];
if (!ereg("^[?[0-9.]+]?$", $emailParts[1])) {
if (OS_IS_WIN && version_compare(PHP_VERSION, '5.3.0') < 0) {
@exec('nslookup -type=MX '.escapeshellcmd($emailParts[1]), $output);
foreach($output as $line){
if (preg_match('/^'.$emailParts[1].'/',$line)) { return true; }
}
}
else if(checkdnsrr($domain,'MX')) {
return true;
}
}
else {
return true;// it is an ip...
}
}
}
return false;
}

Sample usage:
<?php
if (isset($_POST['email'] && !empty($_POST['email'])) {
if (test_email_with_mx($_POST['email'])) {
echo 'Email is valid!';
}
else {
echo 'Invalid email supplied!';
}
?>

Latest News

Clients Say

  • Neil Acheampong

    UnicornCMS to me is the fastest and easiest to use platform out there. I am not a progra...

  • Mark McFarlan

    They give us a great service for the best price. Their quick and proficient support was a...

  • Mike

    You guys are really great! Using your services is wonderful. I already recommended your C...

  • George

    I just wanted to drop in and provide testimony to the excellent web design services you g...

Latest Articles