'PHP FILTER_VALIDATE_EMAIL does not work correctly

I'm using PHP 5.3.10. This is the code:

<?php
$email = "[email protected]";
if (filter_var($email, FILTER_VALIDATE_EMAIL))
        echo "Email: ".$email." correct";
else
        echo "email not correct";
?>

It returns: "Email: [email protected] correct.

I think that a top level domain with only one character is not correct (I'm not aware of one-character-length TLD according to this list: http://data.iana.org/TLD/tlds-alpha-by-domain.txt).

So, FILTER_VALIDATE_EMAIL filter is working correctly or not?



Solution 1:[1]

FILTER_VALIDATE_EMAIL is not supporting PHP 5.2.14

Solution 2:[2]

There is a PHP class on google code for validating email addresses:

http://code.google.com/p/php-email-address-validation

You can use it like

include('EmailAddressValidator.php');
$validator = new EmailAddressValidator;
if ($validator->check_email_address('[email protected]')) { 
    // Email address is technically valid 
} else {
    // Email not valid
}

Solution 3:[3]

FILTER_VALIDATE_EMAIL can only tell you if the address is formatted correctly.

Consider these examples

// "not an email" is invalid so its false.
php > var_export(filter_var("not an email", FILTER_VALIDATE_EMAIL));
false
// "[email protected]" looks like an email, so it passes even though its not real.
php > var_export(filter_var("[email protected]", FILTER_VALIDATE_EMAIL));
'[email protected]'
// "[email protected]" passes, gmail is a valid email server,
//  but gmail require more than 3 letters for the address.
var_export(filter_var("[email protected]", FILTER_VALIDATE_EMAIL));
'[email protected]'

So FILTER_VALIDATE_EMAIL is only good at telling you when it's completely wrong, not when it's right.

You will need to use a service like Real Email which can do indepth email address validation.

// [email protected] is invalid because gmail require more than 3 letters for the address.
var_export(file_get_contents("https://isitarealemail.com/api/email/[email protected]"));
'{"status":"invalid"}'

// [email protected] is valid
var_export(file_get_contents("https://isitarealemail.com/api/email/[email protected]"));
'{"status":"valid"}'

For a more see https://docs.isitarealemail.com/how-to-validate-email-addresses-in-php

Solution 4:[4]

I chose to use :

<?php
$email =$argv[1];$result= is_valid_email($email); echo $result;
function is_valid_email($email) { return preg_match('/^(([^<>()[\]\\.,;:\s@"\']+(\.[^<>()[\]\\.,;:\s@"\']+)*)|("[^"\']+"))@((\[\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\])|(([a-zA-Z\d\-]+\.)+[a-zA-Z]{2,}))$/', $email); }
?>

in my forum software https://github.com/neofutur/MyBestBB/blob/master/include/email.php#L39

but officialy it is : http://www.ex-parrot.com/pdw/Mail-RFC822-Address.html ( longer too)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Sarang
Solution 2 Matthias
Solution 3 Stephen
Solution 4