Created
June 16, 2012 17:09
-
-
Save MikeRogers0/2941972 to your computer and use it in GitHub Desktop.
How to validate an email address with PHP
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
function validEmail($email){ | |
// Check the formatting is correct | |
if(filter_var($email, FILTER_VALIDATE_EMAIL) === false){ | |
return FALSE; | |
} | |
// Next check the domain is real. | |
$domain = explode("@", $email, 2); | |
return checkdnsrr($domain[1]); // returns TRUE/FALSE; | |
} | |
// Example | |
validEmail('[email protected]'); // Returns TRUE | |
validEmail('[email protected]'); // Returns FALSE | |
?> |
You need to add .
to end of domain or it's treated like subdomain of your local domain.
function mxrecordValidate($email){
list($user, $domain) = explode('@', $email);
$arr= dns_get_record($domain,DNS_MX);
if($arr[0]['host']==$domain&&!empty($arr[0]['target'])){
return $arr[0]['target'];
}
}
$email= '[email protected]';
if(mxrecordValidate($email)) {
echo('This MX records exists; I will accept this email as valid.');
}
else {
echo('No MX record exists; Invalid email.');
}
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Not bad. Significantly better than most email regexes floating around the internet.
Besides the problems noted on the
filter_var()
page in the PHP docs regarding internationalized domain names, there are four other problems I see:explode("@", $email)
will not select the domain if the local part of the email address contains an @ symbol, which is valid. Get rid of the limit in theexplode()
call and useend($domain)
to pull just the domain from the email address.fakedomain.com
does not currently have MX records, it does have an A record and once you have fixed 2., your function will start returning TRUE for email addresses at that domain, which is good because it is a valid email address. The TLD.invalid
is designed for cases where you need an invalid domain name.Although the default RR type for
checkdnsrr()
is MX, for clear coding style you should make this explicit and pass "MX" in as the second parameter.