PHP Code

Validate an Email Address With PHP

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;
  }
}

Share

1 Comments

  1. Dear Justin,

    You're amazing voice actor on Yu Yu Hakusho as Yusuke Urameshi. Because that's my number one favorite show of all the other Anime shows I see ever! I just hope it'll come back on Cartoon Network again in the Fall; you're also good from other shows: Fullmetal Alchemist, Dragoon Ball Z, Dragon Ball GT, and… that's all I can think of. You're very funny as Yusuke because through the whole show you come up with some good jokes; but my favorite funny part is when Yusuke and Kuwabara get into so many fights. Excepially, the one on episode five when Yusuke had to ask Kayko, Astuko (Yusuke's mother), and Kuwabara to kiss you. Aw, man! Sick, but funny! Is no wonder why you're also goo d friends with Christopher R. Sabat as the voice of Kuwabara. Keep up the work.

    Sincerly,
    Tayla Drago

Leave a Reply

Your email address will not be published. Required fields are marked *

*
To prove you're a person (not a spam script), type the security word shown in the picture. Click on the picture to hear an audio file of the word.
Anti-spam image