Skip to content

Instantly share code, notes, and snippets.

@MikeRogers0
Created June 16, 2012 17:09
Show Gist options
  • Save MikeRogers0/2941972 to your computer and use it in GitHub Desktop.
Save MikeRogers0/2941972 to your computer and use it in GitHub Desktop.
How to validate an email address with PHP
<?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
?>
@Ladadadada
Copy link

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:

  1. The 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 the explode() call and use end($domain) to pull just the domain from the email address.
  2. If an MX record is not present, you are expected to fall back to the A record of the domain. This is due to the email RFC being specified before the DNS RFC was in wide use.
  3. If an MX record is present, there's no guarantee that its value will in turn have an A record (or an AAAA record). If you are going to do DNS lookups, you should keep going until you get an IP address. Doing DNS lookups at all conflates the notion of validity with deliverability.
  4. Although 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.

@b1rdex
Copy link

b1rdex commented Apr 18, 2018

You need to add . to end of domain or it's treated like subdomain of your local domain.

@panpic
Copy link

panpic commented Sep 8, 2020

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