PHP DevCenter

oreilly.comSafari Books Online.Conferences.

We've expanded our LAMP news coverage and improved our search! Search for all things LAMP across O'Reilly!

Search
Search Tips

advertisement

Listen Print Discuss Subscribe to PHP Subscribe to Newsletters

Quick and Clean PHP Forms
Pages: 1, 2, 3

Deploying the Contact Form

Up to this point, the actual email helper function used by the contact form has remained a mystery. Here is a possible implementation, saved in the aforementioned emailHelper.php file:



function emailValues (&$values) {
    $body = '';
    foreach ($values as $key=>$value) {
      if ($key != 'submit') {
        // replaces underscores with spaces 
        // and capitalizes the resulting words
        $body .= ucwords(ereg_replace('[_]', ' ', $key));
        $body .= "\r\n";
        if ($value == '') {
          $value = '(nothing entered)';
        }
        $body .= $value;
        $body .= "\r\n\r\n";
      }
    }
    
    $to="receiver@domain.com";
    $from="sender@domain.com";
    $subject = $values['subject'];
    $confirmation = "Thank you, your message has been sent.";

    require_once 'Mail.php';
    $smtp = Mail::factory('smtp');
    $headers = array ('From' => $from,
                      'To' => $to,
                      'Subject' => $subject);
    $mail = $smtp->send($to, $headers, $body);

    if (PEAR::isError($mail)) {
      $confirmation = $mail->getMessage() ;
    } 

    echo "<p>" . $confirmation . "</p>";
}

This function also takes advantage of the form field naming convention defined earlier to help format the email in a human-friendly way. Obviously, at the very least, you should consider extracting to a configuration file some of the strings hard-coded in this function.

Another PEAR library, Mail, which in turn requires the PEAR Net_SMTP library, is used instead of the built-in PHP mail function, as this approach is more flexible and easier to use in some circumstances. In particular, many people encounter issues with sendmail, the underling program called by the PHP mail function, and as most servers already have SMTP installed and available, using the SMTP method may be easier. SMTP may or may not be installed on your development machine, however, so consult your distribution's documentation if you encounter problems. On Ubuntu, for example, you can install SMTP using the following command:

sudo apt-get install postfix

HTML_QuickForm itself requires PHP4, the HTML_Common PEAR library and the PEAR base system. If you go to the HTML_QuickForm home page on the PEAR site, you will see that it has been superseded by HTML_QuickForm2, and its developers urge the use of that version. But if like many people, you are deploying onto a PHP4 installation, note that HTML_QuickForm2 requires PHP5, and as the original HTML_QuickForm is still being maintained with bug fixes and security updates, this is likely to be the version you will want to use. HTML_QuickForm2 was originally just a rewrite of HTML_QuickForm to make it work with the PHP5 E_STRICT setting, so the HTML_QuickForm documentation and examples should also be applicable to HTML_QuickForm2 with minimal changes. New functionality is also being added to HTML_QuickForm2, but these features have not been openly documented yet at the time this tutorial was written, so expect to read code to take advantage of any new features.

Finally, consider that often you may not have detailed knowledge of the environment onto which your code will ultimately be deployed or how that environment will be configured, particularly if you are a freelancer. For example, you may know that a client is running Apache2 and PHP4, but you may not know beforehand if they have the appropriate PEAR libraries installed and on the include path. And if the code doesn't work, you look bad, no matter the reason. So consider bundling the required PEAR libraries alongside the scripts that use them, so you can guarantee that all the dependencies will be met. For convenience, this is how the code for this tutorial has been packaged.

Conclusion

At this point, further attempts to optimize the email contact form may result in diminishing returns. As the new subclasses created above are used more, limitations in their implementation will likely become apparent, such as when more complex element types are needed, and further improvements can be made to address these issues as needed.

What has been presented so far is what the author has found helpful in his particular use of this library and for his style of development. As the reader uses HTML_QuickForm, she may choose to integrate the library into her tool set in a different manner that better fits her needs and her development style. The author has merely tried to demonstrate one way in which, with a small investment of time and thought, robust libraries like HTML_QuickForm can be leveraged further in certain contexts.

Of course, there is much more to the HTML_QuickForm library than what has been shown in this tutorial. Complete documentation can be found at the HTML_QuickForm site, including this list of features:

  • More than 20 ready-to-use form elements.
  • XHTML compliant generated code.
  • Numerous mixable and extendable validation rules.
  • Automatic server-side validation and filtering.
  • On request JavaScript code generation for client-side validation.
  • File uploads support.
  • Total customization of form rendering.
  • Support for external template engines (ITX, Sigma, Flexy, Smarty).
  • Pluggable elements, rules, and renderer extensions.

The important thing to remember is that because the optimizations introduced in this tutorial were implemented by wrapping existing functionality in subclasses of HTML_QuickForm, none of the existing functionality in the original super class has been limited in any way. The goal has been to make the most commonly used functionality of HTML_QuickForm a little more convenient to use for developers with certain needs. But if you need to do more than these new methods allow, you can still use any of the documented HTML_QuickForm functionality, including the addElement and addRule methods, as needed, right alongside the new subclass methods introduced in this tutorial.

Additionally, there are links on the HTML_QuickForm site to other PEAR packages that integrate with and extend the functionality of HTML_QuickForm in various ways, including the creation of CAPTCHA elements, database integration, and the creation of multi-page forms. In other words, its unlikely that using HTML_QuickForm, or the subclasses presented here, will limit you in any way as your forms evolve into the future.

Resources

  • Source code for this article

Adam Smith is a senior software architect and project leader at Cornell University in Ithaca New York, where he has been focused most recently on developing Cornell's digital repository and digital preservation infrastructure. He is also the founder of Agile Enterprise Software providing businesses with complete print-to-digital marketing solutions. Read Adam's blog at www.stonemind.net.


Return to ONLamp.


What d you commonly need in a forms package. Does HTML_QuickForm meet these needs?
You must be logged in to the O'Reilly Network to post a talkback.
Post Comment
Full Threads Oldest First

Showing messages 1 through 12 of 12.

  • Another, simple way to add contact form
    2008-10-21 11:28:04  Igor Pro [Reply | View]

    All you need is to have online database, and interface to access to it/add data.

    http://www.mytaskhelper.com - it's a free online database, using which you can create and share online databases.

    Examples of forms is on the main page.
  • HTML_QuickForm_Renderer_Tableless
    2007-11-29 07:23:19  nasser2 [Reply | View]

    Adam, very nice tutorial and it really takes QuickForm to the next step forward. Thus why I want to use your extended class for my form generation.

    However, what do I do to use it with the HTML_QuickForm_Renderer_Tableless class to generate a tableless form. I normally use:


    require_once 'HTML/QuickForm.php';
    require_once 'HTML/QuickForm/Renderer/Tableless.php';

    $form =& new HTML_QuickForm();
    $renderer =& new HTML_QuickForm_Renderer_Tableless();

    // usual code, e.g. new form fields, rules, ...

    $form->accept($renderer);
    echo $renderer->toHtml();

    and worked with QuickForm but not with QuickerForm.

    Would you please help me.

    Thanks,
    Nasser

    • HTML_QuickForm_Renderer_Tableless
      2007-11-29 08:09:55  ajs17@cornell.edu [Reply | View]

      Nasser,

      Thank you for the feedback.

      Not long ago, I also wanted to use a custom renderer, and as I recall, I had to rework my approach a little to account for it.

      I'm going to have to go back and refresh my memory of what I did. The description I then come up with may be long enough that I'll post it on my personal blog and link to it from here.

      Are you under time pressure with this?

      adam
      • HTML_QuickForm_Renderer_Tableless
        2007-11-29 08:15:38  nasser2 [Reply | View]

        Thanks Adama for the prompt reply.

        I have to deliver the project by the weekend.
        • HTML_QuickForm_Renderer_Tableless
          2007-11-29 08:23:06  ajs17@cornell.edu [Reply | View]

          Ouch. I'll try to come up with something today or tomorrow, but I can't guarantee it. When you say "by the weekend" do you literally mean Friday, or do you have the weekend to work on it? As I recall, the changes are small, so once I tell you what I did, you should be able to adapt it pretty quickly to your situation.

          I hope this helps.
          • HTML_QuickForm_Renderer_Tableless
            2007-11-29 16:25:19  ajs17 [Reply | View]

            Nasser,

            I hope this helps:
            http://www.stonemind.net/blog/2007/11/29/adding-custom-renderers-to-html_quickerform/

  • I prefer data-driven to code-driven...
    2007-11-09 14:20:50  GavinAndresen [Reply | View]

    I wrote an OnLamp article last year (Auto-Filled PHP Forms) that takes a more HTML-centric, data-driven approach. A primary requirement was that creative types be able to use a graphical editor to layout the forms and make them look pretty, and that drove the code's implementation. Read it at:
    http://www.onlamp.com/pub/a/php/2006/03/16/autofill-forms.html

    (I do mention HTML_QuickForm in the article...).
  • Adding images to quick form
    2007-10-11 22:28:27  Qis [Reply | View]

    How we can add images to quick form?
  • Alternative form class
    2007-09-16 05:51:15  CraigFrancis [Reply | View]

    Sorry to use a link (page too long to copy/paste).

    But I have created an alternative to this form setup, the theory is to make it as obvious as possible on how it works - primarily because we work in a team of developers, a number of which just focus on HTML code (not PHP)... and it seems to be quite frequent that they need to change something trivial, like making a field optional... and it saves time if they can do it themselves, instead of distracting the PHP developers.

    Although they have to be careful not to remove something that is required for a reason (like the email address on a register form).

    Anyway... my version can be seen here:

    http://www.craigfrancis.co.uk/features/code/phpForm/
  • great article
    2007-09-13 11:28:45  will_macdonald [Reply | View]

    This is VERY similar to the methods I use, even down to looping over the array of results in the process data function.

    It saves a ton of time when making a CMS.

    Will
    • great article
      2007-09-13 11:45:22  ajs17@cornell.edu [Reply | View]

      Thanks for the feedback. Its reassuring to hear that others are using HTML_QuickForm in very similar ways.

      I have really only used HTML_QuickForm on smaller jobs like the contact form example, and would be interested to know how it scales to bigger jobs and at what point employing a fuller framework like CakePHP (or whatever) might make more sense.
      • great article
        2007-09-15 00:00:23  will_macdonald [Reply | View]

        I generally don't use Quickform for the public side, but only for the admin interface. I use HTML_Quickform and HTML_Table to generate a CRUD interface.

        I also use ezSQL to simplify, not abstract, the database work.

        Will


Recommended for You

  1. Cover of PHP Cookbook
    PHP Cookbook
    Print: $44.99
    Ebook: $35.99
  2. Cover of Twitter API: Up and Running
    Twitter API: Up and Running
    Print: $34.99
    Ebook: $27.99
  3. Cover of PHP Pocket Reference
    PHP Pocket Reference
    Print: $9.95
    Ebook: $7.99
  4. Cover of PHP Anthology
    PHP Anthology
    Print: $39.95

Tagged Articles

Be the first to post this article to del.icio.us

Sponsored Resources

  • Inside Lightroom
Advertisement

Sponsored by:

O'Reilly Media

©2009, O'Reilly Media, Inc.
(707) 827-7000 / (800) 998-9938
All trademarks and registered trademarks appearing on oreilly.com are the property of their respective owners.
About O'Reilly
Academic Solutions
Authors
Contacts
Customer Service
Jobs
Newsletters
O'Reilly Labs
Press Room
Privacy Policy
RSS Feeds
Terms of Service
User Groups
Writing for O'Reilly
Content Archive
Business Technology
Computer Technology
Google
Microsoft
Mobile
Network
Operating System
Digital Photography
Programming
Software
Web
Web Design
More O'Reilly Sites
O'Reilly Radar
Ignite
Tools of Change for Publishing
Digital Media
Inside iPhone
makezine.com
craftzine.com
hackszine.com
perl.com
xml.com

Partner Sites
InsideRIA
java.net
O'Reilly Insights on Forbes.com