Skip to content

Instantly share code, notes, and snippets.

@noonat
Created February 21, 2011 22:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save noonat/837779 to your computer and use it in GitHub Desktop.
Save noonat/837779 to your computer and use it in GitHub Desktop.
<?php
/**
* Return true if the email address is valid.
* From http://www.linuxjournal.com/article/9585.
*
* @return bool
*/
function isValidEmail($email) {
$isValid = true;
$atIndex = strrpos($email, '@');
if ($atIndex === false) {
return false;
}
$domain = substr($email, $atIndex+1);
$local = substr($email, 0, $atIndex);
$localLength = strlen($local);
$domainLength = strlen($domain);
if ($localLength < 1 || $localLength > 64) {
// local part length exceeded
return false;
} else if ($domainLength < 1 || $domainLength > 255) {
// domain part length exceeded
return false;
} else if ($local[0] == '.' || $local[$localLength - 1] == '.') {
// local part starts or ends with '.'
return false;
} else if (preg_match('/\\.\\./', $local)) {
// local part has two consecutive dots
return false;
} else if (!preg_match('/^[A-Za-z0-9\\-\\.]+$/', $domain)) {
// character not valid in domain part
return false;
} else if (preg_match('/\\.\\./', $domain)) {
// domain part has two consecutive dots
return false;
} else if (!preg_match(
'/^(\\\\.|[A-Za-z0-9!#%&`_=\\/$\'*+?^{}|~.-])+$/',
str_replace('\\\\', '', $local))) {
// character not valid in local part unless
// local part is quoted
if (!preg_match(
'/^"(\\\\"|[^"])+"$/',
str_replace('\\\\', '', $local))) {
return false;
}
}
// checkdnsrr is not implemented on Windows
if (function_exists('checkdnsrr') && !(checkdnsrr($domain, 'MX') || checkdnsrr($domain, 'A'))) {
// domain not found in DNS
return false;
}
return true;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment