×

Welcome to TagMyCode

Please login or create account to add a snippet.
0
0
 
0
Language: PHP
Posted by: Сергей Шевченко
Added: Feb 26, 2019 8:18 AM
Modified: Feb 26, 2019 8:23 AM
Views: 3795
Tags: email validate
  1. /**
  2.  * Валидация Email, проверка на его существование в мире
  3.  * @param string $email Email для валидации
  4.  * @return bool
  5.  */
  6. function validEmail($email)
  7. {
  8.    $isValid = true;
  9.    $reason = 0;
  10.    $atIndex = strrpos($email, '@');
  11.    if (is_bool($atIndex) && !$atIndex)
  12.    {
  13.       $reason = 1;
  14.       $isValid = false;
  15.    } else {
  16.       $domain = substr($email, $atIndex + 1);
  17.       $local = substr($email, 0, $atIndex);
  18.       $localLen = strlen($local);
  19.       $domainLen = strlen($domain);
  20.       if ($localLen < 1 || $localLen > 64) {
  21.          // local part length exceeded
  22.          $reason = 2;
  23.          $isValid = false;
  24.       } else if ($domainLen < 1 || $domainLen > 255) {
  25.          // domain part length exceeded
  26.          $reason = 3;
  27.          $isValid = false;
  28.       } else if ($local[0] === '.' || $local[$localLen - 1] === '.') {
  29.          // local part starts or ends with '.'
  30.          $reason = 4;
  31.          $isValid = false;
  32.       } else if (preg_match('/\\.\\./', $local)) {
  33.          // local part has two consecutive dots
  34.          $reason = 5;
  35.          $isValid = false;
  36.       } else if (!preg_match('/^[A-Za-z0-9\\-\\.]+$/', $domain)) {
  37.          // character not valid in domain part
  38.          $reason = 6;
  39.          $isValid = false;
  40.       } else if (preg_match('/\\.\\./', $domain)) {
  41.          // domain part has two consecutive dots
  42.          $reason = 7;
  43.          $isValid = false;
  44.       } else if (!preg_match('/^(\\\\.|[A-Za-z0-9!#%&`_=\\/$\'*+?^{}|~.-])+$/',
  45.                  str_replace("\\\\", '', $local))) {
  46.          // character not valid in local part unless
  47.          // local part is quoted
  48.          if (!preg_match('/^"(\\\\"|[^"])+"$/',
  49.              str_replace("\\\\", '', $local))) {
  50.             $reason = 8;
  51.             $isValid = false;
  52.          }
  53.       }
  54.      
  55.       if ($isValid && !(checkdnsrr($domain, 'MX') || checkdnsrr($domain, 'A'))) {
  56.          // domain not found in DNS
  57.          $reason = 9;
  58.          $isValid = false;
  59.       }
  60.    }
  61.    
  62.    if (!$isValid) {
  63.      $msg = sprintf('Email validation failed (%s) with reason %s', $email, $reason);
  64.      logVar($msg);
  65.    }
  66.    
  67.    return $isValid;
  68. }
  69.