Validate Email Address in PHP

It’s a common task but one that I haven’t looked at in as much detail as this devshed article. There’s a few bugs in the code, and a function was posted to the comments that’s all over the place.. here’s the same PHP function, cleaned up, to verify an email address. Note that it won’t work in Windows as-is because “checkdnsrr()” isn’t available on Windows platforms. (Remove the \ characters from before the ” characters surrounding the regex.. WordPress adds them when I post this. *grrr*)

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

Comments

comments

24 Replies to “Validate Email Address in PHP”

  1. Ah, you just happened to bump into my pet peeve:

    + is actually a legal character in the user part of an adress. It is even the example given for recipient_delimiter in postfix’s documentation.

    There are probably a lot of other valid characters that the checker doesn’t accept, but since I use + for my own adresses, that is what I look for. In my opinion, it is usually better to err on the side of caution and never make a false negative. After all, if a form keeps responding with “invalid email” when the user has entered his address, that user is likely to go away and never come back.

    The only low-maintenance regexp that will accomplish this is the short and simple ^.+@.+\…+$

  2. I’ve adapted this function to check for valid email address without connecting to the remote MTAs, since some of my hosts can’t create external SMTP connections.

    I’ve also improved the regexp to allow for + and = mailbox delimiters, by substitute the regexp above for this:

    “/^([a-zA-Z0-9])+([a-zA-Z0-9\.\\+=_-])*@([a-zA-Z0-9_-])+([a-zA-Z0-9\._-]+)+$/”

  3. I THINK I MIGHT COMMIT SUICIDE CAUSE LIFE IS SO HARD TO BEAR (Only Joking)
    I am gay you see so i demand to see scott as soon as he is release from psychotic ward

  4. Just to let you know that the above post was NOT made by me, but by a little twit by the name of ANTHONY ADAMS aka JOHNNY HARDMAN from the UK. This little femmy little girl is jealous of my video collection and has been trying to get some copies from me and since I won’t deal with little butt lickers like him, he has been posting under my name. Not only that but he has signed my OLD email address up for junk mail after junk mail, but the laugh’s on him, I have a new email address and he is wasting his life away thinking he is being clever. Oh well……..at least I know I have a life.

  5. Just to let you know that the above post was NOT made by me, but by a little twat by the name of GARY BELICH AKA SCOTT BUNNY from the US. This little femmy little girl is jealous of my video collection and has been trying to get some copies from me and since I won’t deal with little butt lickers like him, he has been posting under my name. Not only that but he has signed my OLD email address up for junk mail after junk mail, but the laugh’s on him, I have a new email address and he is wasting his life away thinking he is being clever. Oh well……..at least I know I have a life.

  6. You’re so funny Johnny Hard-On. SO FUNNY, everybody forgot to laugh. Hope life is treating you well. My video collection is far superior to yours and everybody else’s, and you know it. Too bad you screwed things up because you’ll never know the cool treasures I’ve gotten since the time you phuked up. HA HA HA……your loss, not mine.
    TAKE CARE, LITTLE GIRL!

  7. yeah the valid email characters are actually a much fuller list which many web sites don’t bother to learn about.. according to this article,

    http://en.wikipedia.org/wiki/E-mail_address

    and RFC 2822,

    http://tools.ietf.org/html/rfc2822

    the local (first, before the ‘@’) part of an email address may contain these characters:

    * Uppercase and lowercase letters (case sensitive)
    * The digits 0 through 9
    * The characters ! # $ % * / ? | ^ { } ` ~ & ‘ + – = _
    * The character . provided that it is not the first or last character in the local-part.

    for me personally, it’s a pain when web site designers don’t bother to learn about this, because i do have an email address with a plus sign in it.

    i did write one web site admin about it and he replied that they just didn’t allow these characters “for security reasons”. i asked him whether it was possible to add in code to escape them out, and he just replied ‘yes’. so it wasn’t security, it’s just laziness. granted, the regexp for taking all these characters into consideration would be a choice morsel.. anyone? 🙂

  8. This code is not working proper. i hosted on linux also.. on invalid domain it showing error. and username invalid case.. its simply say valid… plz help me for original code.

  9. I’m sorry m’buckos but not a single one of those regex validated an email addres of name at domain dot com which suggests to me trying too hard. Thanks anyway though.

  10. this is really a nice code and I badly needed for my website, but, one thing that I don’t understand is that IF MX IS BAD, THE MAIL ADDRESS IS BAD TOO, while the domain may exist and be found running.

    then why return true ?

  11. Hey, I tried this script above however it doesn’t matter what e-mail I type, with different servers too, I just get a fsockopen timeout after about 25 seconds?

    Any idea whats causing that?

  12. turns out most providers don’t allow opening port 25 to their users because its a security issue. Great if you have your own dedicated server or VDS as you can re-enable it but otherwise, not of much use using the fsockopen.

Leave a Reply