[Tool] Check if an email address is valid – the php way

In an older post we talked about checking the validity of an email address.

Now let’s make a php function to automate this task. We can use this type of validation to check for example if a user is using a correct address when registering for a service.

The code is explained.

<?php
/*
email_validation.php
Coded by: Pentest ROMANIA; Dan Catalin VASILE; http://www.pentest.ro
*/

function email_validation($email)
{
 //Some vars we will need later
 $timeout = 5; // how much to wait for MX connection in seconds
 $helo = "helo example.com\r\n"; // helo string, feel free to modify but keep in mind that \r\n are necessary at the end of the string to send CR
 $mailfrom = "mail from: <[email protected]>\r\n"; // some mail and the domain used before, preferably a valid one

 //First we'll do a quick string validation
 if(filter_var($email, FILTER_VALIDATE_EMAIL))
  {
   //split the email address by the @ sign
   $email_str = explode ("@",$email); 
   //check for MX records
   if (getmxrr($email_str, $mxhosts)) //you could also check the weights of the MX hosts, some other time for me maybe
    {
    
    //opening sock connection to the forst MX host 
    $sock = fsockopen ( $mxhosts[0], 25, $errno, $errstr, $timeout);
     if (!$sock)
     {
      return "INVALID. COULD NOT OPEN CONNECTION TO MX HOST. ERROR: ".$errstr.$errno;
     }
     else
     {
      //sending commands to the MX host
      fwrite ($sock,$helo);
      fwrite ($sock,$mailfrom);
      $rcpt = "rcpt to: <".$email.">\r\n";
      fwrite ($sock,$rcpt);
      //reading responses
      for($j=0;$j<4;$j++)
       {
        $r[$j] = fgets($sock);
      }
      //exploding the last response line which should contain the answer we're looking for
      $r1=explode(" ",$r[3]);
      if($r1[0]=="250")
       return "VALID"; //according to the RFC "250" means valid
      else
       {
        echo "INVALID. ERROR CODE FROM MX SERVER: ".$r1[0];
       }
     }

    }
   else
    return "INVALID. NO MX RECORDS FOUND"; 
   
  } 
 else 
  return "INVALID EMAIL ADDRESS"; // the string submitted to filter_var is invalid 

} 

?>

Leave a Reply