Validating Emails with PHP

Often times you will have a contact form on your site. When asking for customer email addresses you may want to check for correctness to make sure they have not forgotten an important part that will leave the email useless. Below is the code that I use to check for valid emails:

// VALIDATE EMAIL ADDRESS TO CHECK FOR CORRECT FORMAT
function check_email_address($email) {
	// First, we check that there's one @ symbol, and that the lengths are right
	if (!ereg("^[^@]{1,64}@[^@]{1,255}$", $email)) {
		// Email invalid - wrong number of characters in one section, or wrong number of @ symbols.
		return false;
	}
	// Split it into sections to make life easier
	$email_array = explode("@", $email);
	$local_array = explode(".", $email_array[0]);
	for ($i = 0; $i < sizeof($local_array); $i++) {
		if (!ereg("^(([A-Za-z0-9!$%&'*+/=?^_`{|}~-][A-Za-z0-9!$%&'*+/=?^_`{|}~\.-]{0,63})|(\"[^(\\|\")]{0,62}\"))$", $local_array[$i])) {
			return false;
		}
	}
	// Check if domain is IP. If not, it should be valid domain name
	if (!ereg("^\[?[0-9\.]+\]?$", $email_array[1])) {
		$domain_array = explode(".", $email_array[1]);
		if (sizeof($domain_array) < 2) {
			return false; // Not enough parts to domain
		}
		for ($i = 0; $i < sizeof($domain_array); $i++) {
			if (!ereg("^(([A-Za-z0-9][A-Za-z0-9-]{0,61}[A-Za-z0-9])|([A-Za-z0-9]+))$", $domain_array[$i])) {
				return false;
			}
		}
	}
	return true;
}

then you can check any email address using:

if (!check_email_address($email)) {
	$error = 'This email is invalid!';
}

Hopefully this helps, I use this a lot in my coding. If you see something it might not catch, let me know.

Share and Enjoy:
  • Print this article!
  • Digg
  • del.icio.us
  • Facebook
  • Mixx
  • RSS
  • Tumblr

One Response

Justin says:

This is a handy little reference that I went ahead and bookmarked! This code is useful on just about any site that you will build.

leave comment