Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
<?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
You can’t perform that action at this time.