PHP : Fonction validEmail

Coder une fonction en PHP vérifiant la validité d'une adresse mail

 

Cette fonction permet de s'assurer que l'adresse email qu'un tiers vous fournit est valide.

 

<?php
function validEmail( $mail ) {

        $mail = filter_var( $mail, FILTER_VALIDATE_EMAIL );

        $max = 320;     // selon la RFC, ne peut comporter plus de 320 caractères
        $port = 25;     // port POP3
        $atom   = '[-a-z0-9!#$%&\'*+\\/=?^_`{|}~]';     // caractères autorisés avant l'arobase (nom utilisateur)
        $domain = '([a-z0-9]([-a-z0-9]*[a-z0-9]+)?)'; // caractères autorisés après l'arobase (nom de domaine)

        $regex = '/^'.$atom.'+'.'(\.'.$atom.'+)*'.'@'.'('.$domain.'{1,63}\.)+'.$domain.'{2,63}$/i';

        if( strlen( $mail ) >= $max ) return FALSE;
        else {
                if( preg_match( $regex, $mail ) ) {
                        list( $user, $domain ) = split( '@', $mail );

                        if( strlen( $user ) > 64 ) return FALSE; // ne doit pas comporter plus de 64 caractères
                        if( strlen( $domain ) > 255 ) return FALSE;     // ne doit pas comporter plus de 255 caractères

                        if( !checkdnsrr( $domain, 'MX' ) ) return FALSE; // si le serveur MX ne répond pas

                        if( !fsockopen( $domain, $port, &$errno, &$errstr, 30 ) ) return FALSE;
                        else return TRUE;

                }
                else return FALSE;
        }
}
?>
 

 

À utiliser ainsi :


<?php
if( validEmail( $yourmail ) ) instructions;
// ou
$mail = validEmail($yourmail);
if( $mail ) instructions;
?>
 

 

 


<<| Page : PHP : function : validEmail : |


 

 

^ Haut de page ^