PHP
  Home arrow PHP arrow Page 6 - Email Address Verification with PHP
Dev Shed Forums 
Administration  
AJAX  
Apache  
BrainDump  
DHTML  
Flash  
Java  
JavaScript  
Multimedia  
MySQL  
Oracle  
Perl  
PHP  
Practices  
Python  
Reviews  
Security  
Style-Sheets  
Web Services  
XML  
Zend  
Zope  
Forums Sitemap 
IBM® developerWorks 
Sun Developer Network 
Dedicated Servers 
E-Commerce Hosting 
Linux Web Hosting 
Managed Hosting 
Small Business Hosting 
Moblin 
JMSL Numerical Library 
VPS Hosting 
Weekly Newsletter

 
Developer Updates  
Free Website Content 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us Get Paid 
Request Media Kit
Contact Us 
Site Map 
Privacy Policy 
Support 
 USERNAME
 
 PASSWORD
 
 
  >>> SIGN UP!  
  Lost Password? 
PHP

Email Address Verification with PHP
By: Alejandro Gervasio
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 4 stars4 stars4 stars4 stars4 stars / 159
    2005-02-08

    Table of Contents:
  • Email Address Verification with PHP
  • Validating the proper format of an email address
  • Validating email domains with checkdnsrr()
  • Customizing checkdnsrr()
  • Using getmxrr() for validation
  • Empowering validation with fsockopen()

  • Rate this Article: Poor Best 
      ADD THIS ARTICLE TO:
      Del.ici.ous Digg
      Blink Simpy
      Google Spurl
      Y! MyWeb Furl
    Email Me Similar Content When Posted
    Add Developer Shed Article Feed To Your Site
    Email Article To Friend
    Print Version Of Article
    PDF Version Of Article
     
     
    ADVERTISEMENT


    Email Address Verification with PHP - Empowering validation with fsockopen()


    (Page 6 of 6 )

    In order to find out whether an email domain is really in use, we’re going to take advantage of PHP’s fsockopen() function, which is used to open domain socket connections over the Internet. This serves our purposes handily, since we might try opening a socket connection to the mail server identified with the given domain. If the socket connection is successfully opened, then the supplied domain is currently in use.

    The format for fsockopen() is the following:

    int fsockopen ( string hostname, int port [, int errno [, string errstr [, float timeout]]]);

    The function, when used for Internet domains, will open a TCP socket connection to the provided host name on the supplied port, and return a file pointer corresponding to that host. If the call fails, it will return false, and if the optional errno and errstr arguments are present, they will be set to indicate the actual system level error that occurred while performing the call. The optional timeout parameter can be used to set a timeout in seconds for the connect system call. 

    Having taken a look at what this function does, it’s feasible to open a socket connection on port 25 (the default port for SMPT servers) to the given domain for a user’s email address in the following manner:

    If(!fsockopen($domain,25,$errno,$errstr,30)) {
     return false;
    }

    Here we’re trying to open a socket connection to the provided domain on port 25, setting a timeout of 30 seconds for the connection. If the connection is successfully established, the function will return true, which means that the SMTP server is up and running, the email domain is real and, hopefully, there is a valid user for that domain. If the connection fails, the function will return false, either indicating that the domain is not being used, at least for the moment that we attempted to open the socket connection. As you can easily guess, there might be several reasons for a failed result. Even if the user was valid, the mail server might be down, our system might be having its own problems, or other difficulties inherent to any network process might exist.

    Anyway, our rough attempt to enhance the validation process is still a valid effort worth considering. Here’s the checkEmail() function with the new enhancements:

    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)) {
      // gets domain name
      list($username,$domain)=split('@',$email);
      // checks for if MX records in the DNS
      if(!checkdnsrr($domain, 'MX')) {
       return false;
      }
      // attempts a socket connection to mail server
      if(!fsockopen($domain,25,$errno,$errstr,30)) {
       return false;
      }
      return true;
     }
     return false;
    }

    And the code to call the function is listed as follows:

    $email = trim($_POST['email']);  
    if(!checkEmail($email)) { 
    echo 'Invalid email address!';
    }
    else {
     echo 'Email address is valid';
    }

    We have taken a considerable step forward to improve the validation routines within our function.

    To explain what we did step-by-step: once the email address is passed to the function, it is first validated to make sure it matches the regular expression. If the validation is successful, then the address is divided to obtain the email domain.

    Then, the function checks whether the domain is real, looking for MX records in the DNS. Again, if the records are found, the next step is to open a socket connection for that domain on port 25, to determine whether the given domain is in use. If the connection is successful, we’re pretty sure that the email address corresponds to a real domain, which is currently in use, and the user name is potentially valid.
    Any checking process that returns false, will evaluate the function as false too, terminating it, therefore indicating that the supplied email address is not valid.

    Finally we’ve successfully reached our objective, with a few lines of PHP code. Not too bad, huh?

    Summary

    As with many other user data, email addresses are certainly pretty hard to validate. We’re not completely sure that what a visitor is giving us is valid input. However, as reviewed in this article, using several powerful PHP network functions combined is a great way to make the validation process a relatively painless task. Additionally, we’ve taken an instructive approach for some other concepts, such as working with lookup functions and sockets, even though we only scratched their surfaces. Thus, the next time you need to implement email verification in your PHP applications, don’t forget these invaluable tools. They're really worthwhile.


    DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware.

       ·  As described in the article, the whole function might be included as a new method...
       · Hello,Nice but its not working for me. Its not getting any furter...
       ·  Hello, The regular expression seems to work fine. Did you try using another email...
       · You should remove spaces from the regular expression, use this...
       ·  The pattern seems to work. Have you tried with other pattern? Regards...
       · In section 6 the author opens a connection on the SMTP port directly to the domain...
       ·  Hi, The revamped version of the function is quite good. Good job.
       ·  Hi again, When I initially wrote the email verification function, I just...
       · here is the above code as a...
       · However the class is overall well defined, email format verfification is redundant...
       · can you show an example of the & usage you are describing.
       · Ok. Using the given class example, you should instantiate the class in...
       · I love the class and find it useful, but I have one problem.If the domain isn't...
       · I saw that too.when calling the last part of the class try using the...
       · Hi, If you don't want to see the warnings generated by PHP functions, just use...
       · There are a lot of allowed characters for the local part of the email address that...
       · Just thinking...This verification would fail if the client uses an external...
       · Hi all,The same concept came to my mind about making sure username validity....
       ·  That's a good reference to the allowable characters for the firs part of an email...
       · Firewalled or not, any server that accepts mail from any address on the Internet...
       · Sure I know that Simple Mail Transport Protocol is for sending email. Andthat's...
       ·  I point to myself, SMTP:Simple Mail Transfer Protocol :-)
       · The goal of email validation would be one of two things. First to catch typo's. ...
       · I've read with interest your commnents about email address verification, and I think...
       · the original regex in the article doesnt work whatsoever (returns false...
       · Thank you for the useful feedback. According to what you point in the regexp, it...
       · I agree completely that this method is very pointless. Sending an email to the user...
       · Been following this with a heck of a lot of interest. Has the 'final' code been...
       · I think someone should at least mention performance. The final solution can add...
       · Hey all,I've been looking into email verification and cannot seem to find...
       · Hello Matt,Thank you for reading and commenting on my article. With reference to...
       · Why do people write articles from the begining that is not in fuction?Stupid!
       · There's no need to post aggressive comments. If you don't like what you read, then...
       · Happening to me too.
       · Thanks for comenting on this article. I have two suggestions for this issue: first,...
       · Can anyone paste the complete codes in here? I m blurred already with different...
       · Hello,Thank you for posting your message here. Now, below there's the complete...
       · I just came across this now, I was searching for a way to validate emails in php as...
       · Thank you for your useful comments regarding my article. Yeap, according to the...
       · HI. I have tried this script and other scripts. But usually I receive the same...
       · Hi,Thank you for commenting here. The socket connection error you're getting may...
       · I think this validation overall is good in terms of showing the usability of some of...
       · First off, I'd like to thank you for posting your comments here. Now, concerning...
       · Am new to PHP programming, but am having a ball learning. Am in the early stages of...
       · Hi Tom,First off, I’d like to thank you for introducing your extensive comments...
       · I was using a simple double "if" to check for the @ + . signs, but i wanted a more...
       · Definitively, your reg expression seems to work better than the one shown in the...
       · Come ON, DevShed!I'm figuring the author MUST have tested the regex while...
       · Thank you for your feedback on my article. Yeaph, you’re correct concerning the...
       · Thanks to all of you for sharing your knowledge, it really is of great help. It...
       · Thank you for commenting on my PHP article. Now, I’d suggest you the following...
       · What about this additional function:function check ($host,$user){ $fp =...
       · Hello Martin,Thank you for posting your comments here. And with reference to...
       · Hello Alejandro,Thanks for your article.This function isn't from me. I...
       · Hi again Martin,I'd like to thank you again for your kind comments on my PHP...
       · Martin - thanks for sharing this with us. I've been looking in several places for...
       · I like the double opt-in for first-time user registration - check email has valid...
       · Hi Caroline,Thanks for posting your detailed, yet easy-to-follow description on...
     

       

    PHP ARTICLES

    - Validating Web Forms with the Code Igniter P...
    - Output Buffering
    - Paginating Database Records with the Code Ig...
    - HTTP Headers in Web Development
    - Project Management: Administration
    - Building a Database-Driven Application with ...
    - User Authentication for a Project Management...
    - Introduction to the CodeIgniter PHP Framework
    - Adding Users for a Project Management Applic...
    - Migrating Class Code for a MIME Email to PHP...
    - Login and Logout Authentication for a Projec...
    - Composing Messages in HTML for MIME Email wi...
    - Project Management: Authentication
    - A Better Way to Determine MIME Types for MIM...
    - Project Management Overview





    © 2003-2008 by Developer Shed. All rights reserved. DS Cluster 1 hosted by Hostway