Email Validation in PHP

pradeep's Avatar author of Email Validation in PHP
This is an article on Email Validation in PHP in PHP.
Title says it all but to reemphasize that below PHP code block validate an email address. Its always good to have a client side validation for faster user responses but backend check is also needed for user not having client side scripting on.

Code: PHP
<?php
    function emailsyntax_is_valid($email) {
      $to_work_out = explode("@", $email);
      if (!isset($to_work_out[0])) return FALSE;
      if (!isset($to_work_out[1])) return FALSE;
   
      $pattern_local = '^([0-9a-z]*([-|_]?[0-9a-z]+)*)(([-|_]?)\.([-|_]?)[0-9a-z]*([-|_]?[0-9a-z]+)+)*([-|_]?);
      $pattern_domain = '
^([0-9a-z]+([-]?[0-9a-z]+)*)(([-]?)\.([-]?)[0-9a-z]*([-]?[0-9a-z]+)+)*\.[a-z]{2,4} ;
      $match_local = eregi($pattern_local, $to_work_out[0]);
      $match_domain = eregi($pattern_domain, $to_work_out[1]);
   
      if ($match_local && $match_domain) {
        return TRUE;
      }
      return FALSE;
    }
    ?>

Use the function like this :

Code: PHP
if (emailsyntax_is_valid($email)) {
      echo "Ok";
    }
   
    // OR
   
    if (!emailsyntax_is_valid($email)) {
      echo "Invaild";
    }