Validate an Email Address With PHP

by admin on July 24, 2009 · 0 comments

Here is a full-blown function to validate email addresses with regular expressions and a DNS lookup on the domain to make sure that it's not just in valid format, but actually a valid mail server!

The regular expression allows for + and = mailbox delimiters. The will not dns lookup will not work on Windows servers.

function checkEmail($email)
{
  // checks proper syntax
  if(!preg_match("/^([a-zA-Z0-9])+([a-zA-Z0-9.+=_-])*@([a-zA-Z0-9_-])+([a-zA-Z0-9._-]+)+$/", $email))
  {
        echo($email);
    return false;
  }     
       
  // gets domain name
  list($username,$domain)=split('@',$email);
  // checks for if MX records in the DNS
  $mxhosts = array();
  if(!getmxrr($domain, $mxhosts))
  {
    // no mx records, ok to check domain
    if (!fsockopen($domain,25,$errno,$errstr,30))
    {
      return false;
    }
    else
    {
      return true;
    }
  }
  else
  {
    // mx records found
    foreach ($mxhosts as $host)
    {
      if (fsockopen($host,25,$errno,$errstr,30))
      {
        return true;
      }
    }
    return false;
  }
}

Previous post:

Next post: