<?php
$emailAddr = "test@test.com";
$isDebug = true;
// logic stolen shamelessly from an article in linuxjournal.com www.linuxjournal.com/article/9585
// return true if valid, false if not
// set the error code to indicate the problem if not
// 5 - no '@' found
// 10 - email address name is longer than 64
// 15 - email domain name is longer than 64
// 20 - email address name begins or ends with a '.'
// 25 - email address name has two consecutive dots '..'
// 30 - invalid character in domain
// 35 - domain has two consecutive dots '..'
// 40 - invalid character in address name
// 45 - domain not found in DNS
$errorCode = 0;
$isValid = true;
$atIndex = strrpos($emailAddr, "@");
if (is_bool($atIndex) && !$atIndex) {
if ($isDebug)
print $emailAddr . "no '@' found<br>";
$errorCode = 5;
$isValid = false;
} else {
$domain = substr($emailAddr, $atIndex+1);
$local = substr($emailAddr, 0, $atIndex);
$localLen = strlen($local);
$domainLen = strlen($domain);
if ($localLen < 1 || $localLen > 64) {
if ($isDebug)
print $emailAddr . " -local part length exceeded<br>";
$errorCode = 10;
$isValid = false;
} else if ($domainLen < 1 || $domainLen > 255) {
if ($isDebug)
print $emailAddr . " -domain part length exceeded<br>";
$errorCode = 15;
$isValid = false;
} else if ($local[0] == '.' || $local[$localLen-1] == '.') {
if ($isDebug)
print $emailAddr . " -local part starts or ends with '.'<br>";
$errorCode = 20;
$isValid = false;
} else if (preg_match('/\\.\\./', $local)) {
if ($isDebug)
print $emailAddr . " -local part has two consecutive dots<br>";
$errorCode = 25;
$isValid = false;
} else if (!preg_match('/^[A-Za-z0-9\\-\\.]+$/', $domain)) {
if ($isDebug)
print $emailAddr . " -character not valid in domain part<br>";
$errorCode = 30;
$isValid = false;
} else if (preg_match('/\\.\\./', $domain)) {
if ($isDebug)
print $emailAddr . " -domain part has two consecutive dots<br>";
$errorCode = 35;
$isValid = false;
} else if (!preg_match('/^(\\\\.|[A-Za-z0-9!#%&`_=\\/$\'*+?^{}|~.-])+$/', str_replace("\\\\","",$local))) {
if ($isDebug)
print $emailAddr . " -character not valid in local part unless local part is quoted<br>";
if (!preg_match('/^"(\\\\"|[^"])+"$/',str_replace("\\\\","",$local))) {
$errorCode = 40;
$isValid = false;
}
}
if ($isValid && !(checkdnsrr($domain,"MX") || checkdnsrr($domain,"A"))){
if ($isDebug) {
print $emailAddr . " -domain not found in DNS<br>";
$errorCode = 45;
$isValid = false;
}
}
}
print $isValid;
?>