PHP – Email Validation for Fake DNS

The following php example helps you to checks for fake DNS as well as utilizes regex functions to 
check the string for proper length & characters.

Code Example:

<?php
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);
	  $localLen = strlen($local);
	  $domainLen = strlen($domain);
	  if ($localLen < 1 || $localLen > 64){
	  	$isValid = false;
	  }
	  else if ($domainLen < 1 || $domainLen > 255){
	  	$isValid = false;
	  }
	  else if ($local[0] == '.' || $local[$localLen - 1] == '.'){
	  	$isValid = false;
	  }
	  else if (preg_match('/\\.\\./', $local)){
	  	$isValid = false;
	  }
	  else if (!preg_match('/^[A-Za-z0-9\\-\\.]+$/', $domain)){
	  	$isValid = false;
	  }
	  else if (preg_match('/\\.\\./', $domain)){
	  	$isValid = false;
	  }
	  else if (!preg_match('/^(\\\\.|[A-Za-z0-9!#%&`_=\\/$\'*+?^{}|~.-])+$/', str_replace("\\\\", "", $local))){
		if (!preg_match('/^"(\\\\"|[^"])+"$/', str_replace("\\\\", "", $local))){
	 		$isValid = false;
		}
	  }
	  if ($isValid && !(checkdnsrr($domain, "MX") || checkdnsrr($domain, "A"))){
	 	$isValid = false;
	  }
    }
    return $isValid;
}

if(validateEmail("test@phpmoot.com")){
	echo 'Valid Email';
}
else{
	echo 'Invalid Email';
}
?>

Post to Twitter Post to Digg Post to Facebook Post to Google Buzz Send Gmail