Skip to content

Instantly share code, notes, and snippets.

@sepehr
Last active August 30, 2019 07:57
Show Gist options
  • Star 12 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sepehr/3340008 to your computer and use it in GitHub Desktop.
Save sepehr/3340008 to your computer and use it in GitHub Desktop.
PHP: Email Validation (RFC 2822)
/**
* Verifies the syntax of the given e-mail address.
*
* See RFC 2822 for details.
*
* @param $mail
* A string containing an e-mail address.
*
* @return
* 1 if the email address is valid, 0 if it is invalid or empty, and FALSE if
* there is an input error (such as passing in an array instead of a string).
*/
function valid_email_address($mail)
{
$user = '[a-zA-Z0-9_\-\.\+\^!#\$%&*+\/\=\?\`\|\{\}~\']+';
$domain = '(?:(?:[a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]*[a-zA-Z0-9])\.?)+';
$ipv4 = '[0-9]{1,3}(\.[0-9]{1,3}){3}';
$ipv6 = '[0-9a-fA-F]{1,4}(\:[0-9a-fA-F]{1,4}){7}';
return preg_match("/^$user@($domain|(\[($ipv4|$ipv6)\]))$/", $mail);
}
@Verron
Copy link

Verron commented Sep 2, 2015

Very useful. Have you considered contributing to get PHP's filter_var to follow RFC 2822 and not RFC 822?

@matudelatower
Copy link

how to void dot in matudelatower.@gmail.com?

@p4prawin
Copy link

Above function could not validate emails like John Smith john.smith@example.org which is a standard format of RFC 2822
I have created a function which will validate both.

function validate_email($email) {
  $email_matches = array();

  $from_regex   = '[a-zA-Z0-9_,\s\-\.\+\^!#\$%&*+\/\=\?\`\|\{\}~\']+';
  $user_regex   = '[a-zA-Z0-9_\-\.\+\^!#\$%&*+\/\=\?\`\|\{\}~\']+';
  $domain_regex = '(?:(?:[a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]*[a-zA-Z0-9])\.?)+';
  $ipv4_regex   = '[0-9]{1,3}(\.[0-9]{1,3}){3}';
  $ipv6_regex   = '[0-9a-fA-F]{1,4}(\:[0-9a-fA-F]{1,4}){7}';

  preg_match("/^$from_regex\s\<(($user_regex)@($domain_regex|(\[($ipv4_regex|$ipv6_regex)\])))\>$/", $email, $matches_2822);
  preg_match("/^($user_regex)@($domain_regex|(\[($ipv4_regex|$ipv6_regex)\]))$/", $email, $matches_normal);

  // Check for valid email as per RFC 2822 spec.
  if (empty($matches_normal) && !empty($matches_2822) && !empty($matches_2822[3])) {
    $email_matches['from_name'] = $matches_2822[0];
    $email_matches['full_email'] = $matches_2822[1];
    $email_matches['email_name'] = $matches_2822[2];
    $email_matches['domain'] = $matches_2822[3];
  }

  // Check for valid email as per RFC 822 spec.
  if (empty($matches_2822) && !empty($matches_normal) && !empty($matches_normal[2])) {
    $email_matches['from_name'] = '';
    $email_matches['full_email'] = $matches_normal[0];
    $email_matches['email_name'] = $matches_normal[1];
    $email_matches['domain'] = $matches_normal[2];
  }

  return $email_matches;
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment