PHP Validate Email Address

///PHP Validate Email Address

PHP Validate Email Address

If you have ever needed to validate an email address to see if the format is good then heres a nice function that does that and more up to and including checking the DNS of the domain of the email address to see if its actually a real domain. Though a lot of people will insist that a single one line regex with preg_match() will be more than enough to suffice most peoples needs, which yes this is true. However I am particular about how I handle things and like to cover as many bases as I possibly can to ensure I am not about to get a spam bomb from some bots.\r\n\r\nThis function returns true/false. True = valid email, False = invalid email\r\nExample of use would be\r\n\r\n
\r\nif(validEmail($_POST['email'] !== true){ echo "Error: Email address provided not valid"; }\r\n
\r\nfunction validEmail($email)\r\n	{\r\n		$isValid = true;\r\n		$atIndex = strrpos($email, "@");\r\n		if (is_bool($atIndex) && !$atIndex)\r\n		{\r\n			$isValid = false;\r\n		}\r\n		else\r\n		{\r\n			$domain = substr($email, $atIndex+1);\r\n			$local = substr($email, 0, $atIndex);\r\n			$localLen = strlen($local);\r\n			$domainLen = strlen($domain);\r\n			if ($localLen < 1 || $localLen > 64)\r\n			{\r\n				// local part length exceeded\r\n				$isValid = false;\r\n			}\r\n			else if ($domainLen < 1 || $domainLen > 255)\r\n			{\r\n				// domain part length exceeded\r\n				$isValid = false;\r\n			}\r\n			else if ($local[0] == '.' || $local[$localLen-1] == '.')\r\n			{\r\n				// local part starts or ends with '.'\r\n				$isValid = false;\r\n			}\r\n			else if (preg_match('/\\.\\./', $local))\r\n			{\r\n				// local part has two consecutive dots\r\n				$isValid = false;\r\n			}\r\n			else if (!preg_match('/^[A-Za-z0-9\\-\\.]+$/', $domain))\r\n			{\r\n				// character not valid in domain part\r\n				$isValid = false;\r\n			}\r\n			else if (preg_match('/\\.\\./', $domain))\r\n			{\r\n				// domain part has two consecutive dots\r\n				$isValid = false;\r\n			}\r\n			else if(!preg_match('/^(\\\\.|[A-Za-z0-9!#%&`_=\\/$\'*+?^{}|~.-])+$/', str_replace("\\\\","",$local)))\r\n			{\r\n				// character not valid in local part unless \r\n				// local part is quoted\r\n				if (!preg_match('/^"(\\\\"|[^"])+"$/', str_replace("\\\\","",$local)))\r\n				{\r\n					$isValid = false;\r\n				}\r\n			}\r\n			if ($isValid && !(checkdnsrr($domain,"MX") || checkdnsrr($domain,"A")))\r\n			{\r\n				// domain not found in DNS\r\n				$isValid = false;\r\n			}\r\n		}\r\n		return $isValid;\r\n	}\r\n
By |2014-01-05T10:23:09+00:00March 8th, 2012|Code, PHP|0 Comments

About the Author:

Not much to know about me, I'm a 35+ year old coder, geek, gamer..

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: