Last active
August 30, 2019 07:57
-
-
Save sepehr/3340008 to your computer and use it in GitHub Desktop.
PHP: Email Validation (RFC 2822)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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); | |
} |
how to void dot in [email protected]
?
Above function could not validate emails like John Smith [email protected] 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
Very useful. Have you considered contributing to get PHP's filter_var to follow RFC 2822 and not RFC 822?