Ultimate Email Validation PHP Function


/ Published in: PHP
Save to your folder(s)

Checks for fake DNS as well as utilizes regex functions to check the string for proper length & characters.


Copy this code and paste it in your HTML
  1. <?php
  2. function validateEmail($email)
  3. {
  4. $isValid = true;
  5. $atIndex = strrpos($email, "@");
  6. if (is_bool($atIndex) && !$atIndex)
  7. {
  8. $isValid = false;
  9. }
  10. else
  11. {
  12. $domain = substr($email, $atIndex + 1);
  13. $local = substr($email, 0, $atIndex);
  14. $localLen = strlen($local);
  15. $domainLen = strlen($domain);
  16. if ($localLen < 1 || $localLen > 64)
  17. {
  18. $isValid = false;
  19. }
  20. else if ($domainLen < 1 || $domainLen > 255)
  21. {
  22. $isValid = false;
  23. }
  24. else if ($local[0] == '.' || $local[$localLen - 1] == '.')
  25. {
  26. $isValid = false;
  27. }
  28. else if (preg_match('/\\.\\./', $local))
  29. {
  30. $isValid = false;
  31. }
  32. else if (!preg_match('/^[A-Za-z0-9\\-\\.]+$/', $domain))
  33. {
  34. $isValid = false;
  35. }
  36. else if (preg_match('/\\.\\./', $domain))
  37. {
  38. $isValid = false;
  39. }
  40. else if (!preg_match('/^(\\\\.|[A-Za-z0-9!#%&`_=\\/$\'*+?^{}|~.-])+$/', str_replace("\\\\", "", $local)))
  41. {
  42. if (!preg_match('/^"(\\\\"|[^"])+"$/', str_replace("\\\\", "", $local)))
  43. {
  44. $isValid = false;
  45. }
  46. }
  47. if ($isValid && !(checkdnsrr($domain, "MX") || checkdnsrr($domain, "A")))
  48. {
  49. $isValid = false;
  50. }
  51. }
  52. return $isValid;
  53. }
  54. ?>

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.