Vérifier la validité d'une adresse email

Petit nouveau ! | 2 Messages

31 mars 2014, 11:16

Bonjour,

Ce code ci-dessous vérifie qu'une adresse email est valide. Le second script définit les constantes pour l'affichage des messages d'erreur (adapter l'appel du second script dans le premier).
Laissez un message sous ce topic si ce script vous a été utile ou si vous l'avez adapté à vos besoins ou encore pour dire tout simplement ce que vous en pensez.

Merci.

<?php
/*************************************************************************************************************************

            FUNCTION TO TEST THE VALIDITY OF AN EMAIL ADDRESS



    Author      :   Stéphane-Hervé
    Forum       :   http://inforezo.1fr1.net
    Email       :   shinfo17 [at] gmail [dot] com

    Description :
    
 this function let you warn the user that :
 - a special character was used (but the '_', '-' and '.' which are authorized)
 - the '@' is missing or found more than once
 - the '.' in the domain name is missing
 - the domain name, the suffix or the account name is too short or too long
 - the domain name is wrong (request sent to the DNS server)
    
    Parameter :
     - String : email address to test
    
    Return value :
 - String : errors message formatted for display
 - Integer -1 if email valid

**************************************************************************************************************************/



function  checkEmail($email)
{
        // Inclusion of error messages
        require_once '/controllers/constants/formerrors.php';
        
        $lines = '';

        // splitting of the email address into 3 parts
        // part I : before '@'
        // part II : between '@' and '.'
        // part III : after '.'
        $email_part = split('@',$email);
        $domain = $email_part[1];
        $email_domain = split('\.',$email_part[1]);



    //-------------------------------------------------//
    //    ABOUT THE EXISTENCE OF THE DOMAIN NAME       //
    //-------------------------------------------------//
    
        if ( (isset($email_part[1])) && (!checkdnsrr($email_part[1])) )
        { $lines .= EMAIL_WRONG_DOMAIN_1_ERROR.$email_part['1'].EMAIL_WRONG_DOMAIN_2_ERROR.'\n'; }



    //-------------------------------------------------//
    //       ABOUT THE PRESENCE OF THE AROBASE         //
    //-------------------------------------------------//

        // MISSING @
        if ( substr_count($email, '@') < 1 ) { return EMAIL_ERROR.EMAIL_NO_AROBASE_ERROR.'\n'; }
        // MORE THAN 1 @
        elseif ( substr_count($email, '@') > 1 ) { return EMAIL_ERROR.EMAIL_MANY_AROBASES_ERROR.'\n'; }



    //-------------------------------------------------//
    //    ABOUT THE PRESENCE OF THE DOMAIN NAME'S DOT  //
    //-------------------------------------------------//

        if ( substr_count($email_part[1], '.') < 1 ) { $lines .= EMAIL_NODOT_ERROR.$email_domain['0'].'\n'; }



    //-------------------------------------------------//
    //    ABOUT THE LENGTH OF THE ADDRESS              //
    //-------------------------------------------------//

        // OF THE PART 1
        if ( ($email_part[0] == '') || (strlen($email_part[0]) < 3) )
        { $lines .= EMAIL_NOTENOUGH_CHAR_ERROR.EMAIL_BEFORE_AROBASE_ERROR.$email_part['0'].'\n'; }
        elseif ( ($email_part[0] > 64) )
        { $lines .= EMAIL_TOOMANY_CHAR_ERROR.EMAIL_BEFORE_AROBASE_ERROR.$email_part['0'].'\n'; }

        // OF THE DOMAIN NAME
        if ( ($email_part[1] == '') || (strlen($email_part[1]) < 2) )
        { $lines .= EMAIL_NOTENOUGH_CHAR_ERROR.EMAIL_AFTER_AROBASE_ERROR.$email_part['1'].'\n'; }
        elseif ( ($email_part[1] > 255) )
        { $lines .= EMAIL_TOOMANY_CHAR_ERROR.EMAIL_AFTER_AROBASE_ERROR.$email_part['1'].'\n'; }

        // OF THE FIRST PART OF THE DOMAIN NAME
        if ( strlen($email_domain[0]) < 2 )
        { $lines .= EMAIL_NOTENOUGH_CHAR_ERROR.EMAIL_BEFORE_DOT_ERROR.$email_domain['0'].'\n'; }

        // OF THE DOMAIN NAME'S SUFFIX
        if ( strlen($email_domain[1]) < 2 )
        { $lines .= EMAIL_NOTENOUGH_CHAR_ERROR.EMAIL_AFTER_DOT_ERROR.$email_domain['1'].'\n'; }



    //-------------------------------------------------//
    //    ABOUT THE PRESENCE OF FORBIDDEN CHARACTERS   //
    //-------------------------------------------------//

 // about the presence of non authorized characters
 // (authorized characters are : alphanumeric, dot, hyphen, underscore (.-_).

        // checking with preg_match that the email address begins with an alphanumeric character : ^[[:alnum:]]
        // and that any of the following character is alphanumeric (to the last) : *$
        // if it isnot the case, then an error : !preg_match

        // IN THE FIRST PART OF THE ADDRESS
        if ( !preg_match('`^[[:alnum:],_,\-,.]*$`', $email_part['0']) )
        { $lines .= EMAIL_WRONG_CHAR_1_ERROR.$email_part['0'].'\n'; }

        // IN THE FIRST PART OF THE DOMAIN NAME
        if ( !preg_match('`^[[:alnum:],_,\-,.]*$`', $email_domain['0']) )
        { $lines .= EMAIL_WRONG_CHAR_1_ERROR.$email_domain['0'].'\n'; }

        // IN THE SUFFIX OF THE DOMAIN NAME
        if ( !preg_match('`^[[:alnum:],_,\-,.]*$`', $email_domain['1']) )
        { $lines .= EMAIL_WRONG_CHAR_1_ERROR.$email_domain['1'].'\n'; }

    // returning the result
    if ( $lines == '' ) { return -1; }
    else { return EMAIL_ERROR.$lines; }
}

?>

formerrors.php :
<?php
    /***    ERREURS EMAIL     ***/
    define ('PLEASE' , 'Indiquez, s\'il vous plait :');
    define ('IDENTITY_ERROR' , '- vos prénom et nom');
    
    // adresse email - debut ---
    define ('EMAIL_MISSING_ERROR' , '- votre adresse email.');
    define ('EMAIL_ERROR' , 'votre adresse email est erronée : \n');
    define ('EMAIL_BEFORE_AROBASE_ERROR' , 'avant @ : ');
    define ('EMAIL_AFTER_AROBASE_ERROR' , 'après @ : ');
    define ('EMAIL_BEFORE_DOT_ERROR' , 'apres @ et avant le point \".\" : ');
    define ('EMAIL_AFTER_DOT_ERROR' , 'dans le suffixe du nom de domaine (apres @ et apres le point \".\") : ');
    define ('EMAIL_NOFIRSTPART_ERROR' , '- erreur de la premiere partie (avant @)');
    define ('EMAIL_NO_AROBASE_ERROR' , '- omission de @');
    define ('EMAIL_MANY_AROBASES_ERROR' , '- il y a plus d\'un @');
    define ('EMAIL_NODOT_ERROR' , '- omission du point (\'.\') dans la partie apres @ : ');
    define ('EMAIL_NOTENOUGH_CHAR_ERROR' , '- pas assez de caractères ');
    define ('EMAIL_TOOMANY_CHAR_ERROR' , '- trop de caractères ');
    define ('EMAIL_WRONG_CHAR_1_ERROR' , '- un caractère interdit a été utilisé dans : ');
    define ('EMAIL_WRONG_DOMAIN_1_ERROR' , '- le nom de domaine \"');
    define ('EMAIL_WRONG_DOMAIN_2_ERROR' , '\" n\'existe pas');
    // --- adresse email - fin
    
    define ('MESSAGE_ERROR' , '- votre message');
?>

Petit nouveau ! | 2 Messages

01 avr. 2014, 15:32

Dans les scripts du post précédent, je n'avais pas fait attention que la fonction split, obsolète, avait été utilisée.
Voici donc les scripts réécrits avec :
- explode() en remplacement de split() ;
- '<br /&rt;' en remplacement de "\n", pour un affichage dans une page web.
<?php

/*************************************************************************************************************************

            FUNCTION TO TEST THE VALIDITY OF AN EMAIL ADDRESS



    Author      :   Stéphane-Hervé
    Forum       :   http://inforezo.1fr1.net
    Email       :   shinfo17 [at] gmail [dot] com

    Description :
    
      this function let you warn the user that :
      - a special character was used (but the '_', '-' and '.' which are authorized)
      - the '@' is missing or found more than once
      - the '.' in the domain name is missing
      - the domain name, the suffix or the account name is too short or too long
      - the domain name is wrong (request sent to the DNS server)
    
    Parameter :
       - String : email address to test
    
    Return value :
      - String : errors message formatted for display
      - Integer -1 if email valid

**************************************************************************************************************************/



function  checkEmail($email)
{
        // Inclusion of error messages
        require_once 'controllers/constants/formerrors.php';
        
        $lines = '';

        // splitting the email address into 3 parts
        // part I   : before '@'
        // part II   : between '@' and '.'
        // part III   : after '.'
        $email_part = explode ('@',$email);
        $domain = $email_part[1];
        $email_domain = explode ('.',$email_part[1]);



    //-------------------------------------------------//
    //    ABOUT THE EXISTENCE OF THE DOMAIN NAME       //
    //-------------------------------------------------//
    
        if ( (isset($email_part[1])) && (!checkdnsrr($email_part[1])) )
        { $lines .= EMAIL_WRONG_DOMAIN_1_ERROR.$email_part['1'].EMAIL_WRONG_DOMAIN_2_ERROR.'<br />'; }



    //-------------------------------------------------//
    //       ABOUT THE PRESENCE OF THE AROBASE         //
    //-------------------------------------------------//

        // MISSING @
        if ( substr_count($email, '@') < 1 ) { return EMAIL_ERROR.EMAIL_NO_AROBASE_ERROR.'<br />'; }
        // MORE THAN 1 @
        elseif ( substr_count($email, '@') > 1 ) { return EMAIL_ERROR.EMAIL_MANY_AROBASES_ERROR.'<br />'; }



    //-------------------------------------------------//
    //    ABOUT THE PRESENCE OF THE DOMAIN NAME'S DOT  //
    //-------------------------------------------------//

        if ( substr_count($email_part[1], '.') < 1 ) { $lines .= EMAIL_NODOT_ERROR.$email_domain['0'].'<br />'; }



    //-------------------------------------------------//
    //    ABOUT THE LENGTH OF THE ADDRESS              //
    //-------------------------------------------------//

        // OF THE PART 1
        if ( ($email_part[0] == '') || (strlen($email_part[0]) < 3) )
        { $lines .= EMAIL_NOTENOUGH_CHAR_ERROR.EMAIL_BEFORE_AROBASE_ERROR.$email_part['0'].'<br />'; }
        elseif ( ($email_part[0] > 64) )
        { $lines .= EMAIL_TOOMANY_CHAR_ERROR.EMAIL_BEFORE_AROBASE_ERROR.$email_part['0'].'<br />'; }

        // OF THE DOMAIN NAME
        if ( ($email_part[1] == '') || (strlen($email_part[1]) < 2) )
        { $lines .= EMAIL_NOTENOUGH_CHAR_ERROR.EMAIL_AFTER_AROBASE_ERROR.$email_part['1'].'<br />'; }
        elseif ( ($email_part[1] > 255) )
        { $lines .= EMAIL_TOOMANY_CHAR_ERROR.EMAIL_AFTER_AROBASE_ERROR.$email_part['1'].'<br />'; }

        // OF THE FIRST PART OF THE DOMAIN NAME
        if ( strlen($email_domain[0]) < 2 )
        { $lines .= EMAIL_NOTENOUGH_CHAR_ERROR.EMAIL_BEFORE_DOT_ERROR.$email_domain['0'].'<br />'; }

        // OF THE DOMAIN NAME'S SUFFIX
        if ( strlen($email_domain[1]) < 2 )
        { $lines .= EMAIL_NOTENOUGH_CHAR_ERROR.EMAIL_AFTER_DOT_ERROR.$email_domain['1'].'<br />'; }



    //-------------------------------------------------//
    //    ABOUT THE PRESENCE OF FORBIDDEN CHARACTERS   //
    //-------------------------------------------------//

   // about the presence of non authorized characters
   // (authorized characters are : alphanumeric, dot, hyphen, underscore (.-_).

        // checking with preg_match that the email address begins with an alphanumeric character : ^[[:alnum:]]
        // and that any of the following character is alphanumeric (to the last) : *$
        // if it isnot the case, then an error : !preg_match

        // IN THE FIRST PART OF THE ADDRESS
        if ( !preg_match('`^[[:alnum:],_,\-,.]*$`', $email_part['0']) )
        { $lines .= EMAIL_WRONG_CHAR_1_ERROR.$email_part['0'].'<br />'; }

        // IN THE FIRST PART OF THE DOMAIN NAME
        if ( !preg_match('`^[[:alnum:],_,\-,.]*$`', $email_domain['0']) )
        { $lines .= EMAIL_WRONG_CHAR_1_ERROR.$email_domain['0'].'<br />'; }

        // IN THE SUFFIX OF THE DOMAIN NAME
        if ( !preg_match('`^[[:alnum:],_,\-,.]*$`', $email_domain['1']) )
        { $lines .= EMAIL_WRONG_CHAR_1_ERROR.$email_domain['1'].'<br />'; }

    // returning the result
    if ( $lines == '' ) { return -1; }
    else { return EMAIL_ERROR.$lines; }
}

?>


formerrors.php
<?php
/***    ERREURS EMAIL     ***/
define ('PLEASE' , 'Indiquez, s\'il vous plait :');
define ('IDENTITY_ERROR' , '- vos prénom et nom');

// adresse email - debut ---
define ('EMAIL_MISSING_ERROR' , '- votre adresse email.');
define ('EMAIL_ERROR' , 'votre adresse email est erronée : <br />');
define ('EMAIL_BEFORE_AROBASE_ERROR' , 'avant @ : ');
define ('EMAIL_AFTER_AROBASE_ERROR' , 'après @ : ');
define ('EMAIL_BEFORE_DOT_ERROR' , 'après @ et avant le point \'.\' : ');
define ('EMAIL_AFTER_DOT_ERROR' , 'dans le suffixe du nom de domaine (apres @ et après le point \'.\') : ');
define ('EMAIL_NOFIRSTPART_ERROR' , '- erreur de la premiere partie (avant @)');
define ('EMAIL_NO_AROBASE_ERROR' , '- omission de @');
define ('EMAIL_MANY_AROBASES_ERROR' , '- il y a plus d\'un @');
define ('EMAIL_NODOT_ERROR' , '- omission du point (\'.\') dans la partie après @ : ');
define ('EMAIL_NOTENOUGH_CHAR_ERROR' , '- pas assez de caractères ');
define ('EMAIL_TOOMANY_CHAR_ERROR' , '- trop de caractères ');
define ('EMAIL_WRONG_CHAR_1_ERROR' , '- un caractère interdit a été utilisé dans : ');
define ('EMAIL_WRONG_DOMAIN_1_ERROR' , '- le nom de domaine \'');
define ('EMAIL_WRONG_DOMAIN_2_ERROR' , '\' n\'existe pas');
// --- adresse email - fin

define ('MESSAGE_ERROR' , '- votre message');
define ('ANTISPAM_EMPTY_ERROR' , '- le mot dans le champ antispam');
define ('ANTISPAM_WRONG_ERROR' , 'le mot antispam est erroné');
?>