[PHP] Check if eMail address is correct / validation

Dieser Beitrag ist auch verfügbar in: German

Hello together,

on almost every webpage is a field where the user have to enter his email address. Doesn’t matter if it is a contact form, the registration form for a newsletter or the registration for a member area.

We need to check in every case the email address. If the structure is correct (not that the user accidentally entered the URL of his homepage) and we can check if the domain exist. But unfortunately we can’t check spelling mistakes… or just with an effort which wouldn’t be worthwhile anymore.

Here the simple function to check the email address:

function mailCheck($email) { 
	return preg_match("/^[_a-zA-Z0-9-]+(.[_a-zA-Z0-9-]+)*@[a-zA-Z0-9-.]+.([a-zA-Z]{2,4})$/", $email); 
}

This function will just check if the structure of the email address is correct. It means if the “@” sign is on the right position and if a TLD is in the string. It will not check if the domain (TLD) exist or not.

And here the extended function:

function mailcheckDNS($mail) { 
	$email = htmlspecialchars($mail); 
	$r = false; 
	if(preg_match('/(.*?)@(.*?).(w){2,6}/i', $email)) { 
		$split = explode('@', $email); 
		$split2 = explode('.', $split[1]); 
		if(preg_match('/([a-z]){3,64}/i', $split2[0])) { 
			if(preg_match('/([a-z0-9!"$&/()?~#+.:_-]+){1,64}[^@]/i', $split[0])) { 
				$MXCheck = getmxrr($split[1], $mxhosts); 
				if(!empty($MXCheck)) { 
					$r = true; 
				} 
			} 
		} 
	} 
	return $r; 
}

This function checks now also if the domain exist, with trying to reach it. If it is possible then the result will be positive, if not negative.

There is no 100% sure email check, but what we can check, we should check. Spelling mistakes can’t be checked. But therefore we could let the user enter his email address a second time, to make sure it’s correct.

Best regards
Gordon


Attention: Using my code snippets at your own risk! I assume no warranty for functionality (each server is configured differently. If you have problems then you can leave a comment and we look for a solution.;)

0 replies

Leave a Reply

Want to join the discussion?
Feel free to contribute!

Leave a Reply

Your email address will not be published. Required fields are marked *

*