PHP Email Validation

Here is a simple PHP function that validates an email address. Please read the complete article on how this is achieved at: 

http://www.linuxjournal.com/article/9585?page=0,0

/**
 * Validates an email address.
 *
 * @param string $email the email address to validate
 *
 * @return bool true if the email is valid, false otherwise
 */
function validateEmail($email)
{


$isValid = true;
$atIndex = strrpos($email, "@");

if (is_bool($atIndex) && !$atIndex) {

$isValid = false;

} else {

$domain = substr($email, $atIndex + 1);
$local = substr($email, 0, $atIndex);
$localLength = strlen($local);
$domainLength = strlen($domain);

if (($localLength < 1) || ($localLength > 64)) {

// Local (name part) length exceeded
$isValid = false;

} else if (($domainLength < 1) || ($domainLength > 255)) {

// Domain length exceeded
$isValid = false;

} else if (($local[0] == '.') || ($local[$localLength - 1] == '.')) {

// Local part starts or ends with a dot '.'
$isValid = false;

} else if (preg_match('/\\.\\./', $local)) {

// Local part has two consecutive dots
$isValid = false;

} else if (!preg_match('/^[A-Za-z0-9\\-\\.]+$/', $domain)) {

// Character not valid in domain part
$isValid = false;

} else if (preg_match('/\\.\\./', $domain)) {

// Domain part has two consecutive dots
$isValid = 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))) {

$isValid = false;

}

} else {

if ($domain != "ovi.com") {

$isValid = false;

}

}

if ($isValid && !(checkdnsrr($domain, "MX") || checkdnsrr($domain, "A"))) {

// Domain not found in DNS
$isValid = false;

}

}

return $isValid;

}
By Brian Last updated: 5 August 2010, 11:58