Validate E-mail Addresses

I know this is a topic with 1001 solutions, but I still get asked for an e-mail validation check from time to time, so here is one that I have used in the past. It's a cut above average as it allows very basic validation, confirmation of a valid domain ending or even performs an MX record check to ensure that a mail server is at least set up for the domain in question.

Without further ado:

function check_email($value, $options = null)
{
	$value = trim($value);
 
	$regexp = '/^[a-z0-9\._%+-]+@[a-z0-9\.-]+\.(aero|arpa|asia|biz|cat|com|coop|edu|gov|info|int|jobs|mil|mobi|museum|name|net|org|pro|tel|travel|ac|ad|ae|af|ag|ai|al|am|an|ao|aq|ar|as|at|au|aw|ax|az|ba|bb|bd|be|bf|bg|bh|bi|bj|bl|bm|bn|bo|br|bs|bt|bv|bw|by|bz|ca|cc|cd|cf|cg|ch|ci|ck|cl|cm|cn|co|cr|cu|cv|cx|cy|cz|de|dj|dk|dm|do|dz|ec|ee|eg|eh|er|es|et|eu|fi|fj|fk|fm|fo|fr|ga|gd|ge|gf|gg|gh|gi|gl|gm|gn|gp|gq|gr|gs|gt|gu|gw|gy|hk|hm|hn|hr|ht|hu|id|ie|il|im|in|io|iq|ir|is|it|je|jm|jo|jp|ke|kg|kh|ki|km|kn|kp|kr|kw|ky|kz|la|lb|lc|li|lk|lr|ls|lt|lu|lv|ly|ma|mc|md|me|mf|mg|mh|mk|ml|mm|mn|mo|mp|mq|mr|ms|mt|mu|mv|mw|mx|my|mz|na|nc|ne|nf|ng|ni|nl|no|np|nr|nu|nz|om|pa|pe|pf|pg|ph|pk|pl|pm|pn|pr|ps|pt|pw|py|qa|re|ro|rs|ru|rw|sa|sb|sc|sd|se|sg|sh|si|sj|sk|sl|sm|sn|so|sr|st|su|sv|sy|sz|tc|td|tf|tg|th|tj|tk|tl|tm|tn|to|tp|tr|tt|tv|tw|tz|ua|ug|uk|um|us|uy|uz|va|vc|ve|vg|vi|vn|vu|wf|ws|ye|yt|yu|za|zm|zw)$/i';
 
	if(isset($options['basic']) AND $options['basic'] == true)
	{
		$regexp = '/^[a-z0-9\._%+-]+@[a-z0-9\.-]+\.[a-z]+$/i';
	}
 
	if(preg_match($regexp, $value, $match))
	{
		if(isset($options['mx_check']) AND $options['mx_check'] == true)
		{
			return checkdnsrr($match[1], 'MX');
		}
 
		return true;
	}
 
	return false;
}
 
if(!function_exists('checkdnsrr'))
{
	function checkdnsrr($hostName, $recType = null, $timeout = 4)
	{
		if(!empty($hostName))
		{
			if(!is_null($recType))
			{
				$recType = 'MX';
			}
 
			$command = 'nslookup -type='.escapeshellarg($recType).' -timeout='.$timeout.' '.escapeshellarg($hostName);
			exec($command, $result);
 
			# Check each line to find the one that starts with the host name. If it exists then the function succeeded.
			foreach($result as $line)
			{
				if(preg_match('!^'.$hostName.'!i', $line))
				{
					return true;
				}
			}
		}
 
		return false;
	}
}

The 'check_email' function allows you to pass in an e-mail string (and will currently trim it for you) and an array of options. These are limited to 'mx_check' (check the MX server) and 'basic' (use a simple regexp), but feel free to add your own.

Included is a 'checkdnsrr' function for those systems that do not have it. It does require exec privileges though and you may need to modify the timeout to suit your system (lower is better, but may report false due to timeout, you have been warned!).

As always, hope it helps someone!