PHP Form Processor

Ever since I started building websites I’ve found making forms to be time consuming, tedious and generally boring, and I’m pretty sure most web developers are in a similar situation.

First of all you have your HTML form, which then submits all the data to PHP to be validated etc. You have to write the validation rules for each form field in PHP, and then come up with a system of reporting errors back to the user. With large forms this can get extremely complicated!

Around two years ago I can across a form validator by Simon Willison. This basically lets you write the entire form and it’s validation rules in the html. These rules are then read by PHP, applied to the relevant form fields and so on. It’s a very elegant solution that makes building forms much easier and faster, as well as easier to debug and maintain. I’ve been using this script for the last 2 years and have made various changes to the script along the way to suit my purposes.

However, the script does have it’s down-points. It uses the PHP 4 XML library which to be honest is rubbish! It causes the code to become extremely bloated and unable to handle certain characters such as ampersands (&). This means that as soon as a user enters an ampersand or a character like a dollar, the script would crash!

The script also only supported textfields, and didn’t provide support for radio buttons, checkboxes and select drop-down lists.

With all these positives and negatives in mind I’ve built my own PHP Form Processor from scratch, which I think does the job quite nicely. The script is open source and I’ve provided a tutorial on how to use it.

The script also protects your forms against CSRF (Cross-site request forgery) and form manipulation. Anyway, without futher ado, here is the tutorial..

Requirements

  • PHP 5 with SimpleXML support
  • Session support
  • Cheese on toast

Demonstration

Traditionally an XHTML form input box would look like this:

<input type="text" id="myBox" name="myBox" />

Using my PHP form processor this would be written as:

<element id="myBox">
 <input type="text" />
 <error><strong class="error">!</strong></error>
 <compulsory message="myBox must be filled in" />
 <validate test="alpha" message="myBox must only be letters" />
</element>

At first glance it looks a lot more bloated than the traditional method, so lets take a look at what it’s doing and why it’s better.

When using the form processor all the form items are wrapped in element tags. The element tag tells the form processor that it’s a form field, and also specifies the ID. Within the element tag we define the properties and rules of the form field. In the above example we’re telling the form processor that the form field we want is a text field (<input type=”text” />), as well as defining various rules to apply to the user’s input.

The line  ’<error><strong class=”error”>!</strong></error>’ defines what is displayed when a validation rule fails. In this case a bold exclamation mark would be displayed just after the text field.

The next few lines are the rules which we want to apply to the text field. The compulsory line states that the field must be filled in, and if it’s not present the message ‘myBox must be filled in’ to the user. The validate line states that the user input must only be letters, and if it’s not present the message ‘myBox must only be letters’ to the user.

Many rules can be applied to the form fields. They will be applied to the form field in the order that you define them (top to bottom). For example, if there are 3 rules defined for a form field and the first rule fails then the next 2 rules won’t be applied. Instead the error message for rule 1 will be shown to the user. If the 1st rule runs fine it’ll move onto the 2nd rule etc.

Here is a description of each of the rules available:

Compulsory

Checks whether the user has entered any input or not.

<compulsory message="This field is compulsory" />
Textfield Password Textarea Dropdown list Checkbox Radio button Button
Yes Yes Yes No No No No

Validate

Checks whether the user input matches the format specified. The format can be alpha, alphanumeric or numeric.

<validate test="alpha" message="email must be alpha" />
Textfield Password Textarea Dropdown list Checkbox Radio button Button
Yes Yes Yes No No No No

Regular Expression

Checks whether the user input matches the regular expression specified.

<regexp test="|^[a-zA-Z]*$|" message="email doesn't match the regexp" />
Textfield Password Textarea Dropdown list Checkbox Radio button Button
Yes Yes Yes No No No No

Match

Checks whether the user input matches the user input in another field. Most common usage is for confirming passwords.

<match element="anotherFieldID" message="this field must match another field" />
Textfield Password Textarea Dropdown list Checkbox Radio button Button
Yes Yes Yes No No No No

Callback

Takes the user input and passes it to a PHP function of your choice. The function should take one parameter as a string (the user input), and return Boolean true or false. If the function returns false the error message will be presented to the user.

An unlimited number of callbacks can be defined for each form field - just place them one after another.

<callback function="functionname" message="callback 1 failed" />
Textfield Password Textarea Dropdown list Checkbox Radio button Button
Yes Yes Yes Yes Yes Yes Yes

Summary & goodies!

The entire form and it’s rules are read in by PHP, which then goes through the form and extracts the rules. It then cleans up the form and produces strict XHTML which it outputs to the user. This means they never see the rules and just see standard XHTML markup.

It’s a difficult concept and you might be a bit confused at this point, so it’s probably best just to give you a working example. Here is a simple form which tests some of the functionality available (complete with source-code).

View example form
Download the form processor (version 1.04 - 06/10/2008)

As always I’d love to hear from you, so any thoughts, comments, bugs etc, please post! I’d also like to see examples of where people have used it, so feel free to drop me links!

Tags: , ,

Comments


  1. Gavin Holt

    Hey Rich,

    Having used the old version of your form class, This is a great improvement.
    It truly does save hours of development time and the fact you are releasing it free is even better.

    Thanks

    Gavin!


  2. franco

    Hi

    I downloaded the from processor but I think I don’t have the session thing that is required…what is this? I run it from xampp on localhost. I can see example.php when I run from localhost but not formprocessor.php

    Can you tell me what I”m doing wrong.

    thanx for this free code!


  3. Richard Willars

    Hi Franco,

    All you need to do is download the form processor (from the link above) and extract the contents of the zip file into your website directory. There should be 2 files - testform.php and formprocessor.php. testform.php is the file you’d want to run through xampp.

    I’m unsure of your problem with the sessions - the scripts don’t require anything special aside from normal sessions (I believe xampp has this functionality enabled by default). Could you show me any error messages you are receiving so I can help you further?


  4. Juan Sarabia

    I’m trying but I get this error:

    Parse error: syntax error, unexpected ‘(’, expecting ‘,’ or ‘)’ in /home/ollin/domains/ollinpublicidad.com/public_html/proyectos/tecmei/formprocessor.php on line 53


  5. Richard Willars

    I’ve just released version 1.03 of the form processor. This releases fixes a few bugs and adds some further functionality which will be documented shortly.

    Juan, this should also fix your problem.


  6. wheelibin

    Hi
    This looks just what I’m after and thank you for making it available for free….I have just downloaded it and I am getting the same error as Juan - Parse error: syntax error, unexpected ‘(’, expecting ‘,’ or ‘)’ on line 53 again…..have you any ideas?
    Thanks a lot


  7. Trish

    Where can we download the latest version?


  8. Richard Willars

    wheelibin, you need to make sure you have PHP 5 and simplexml, otherwise you will receive that error.

    Trish, the link to download is at the bottom of the article in the summary section (sorry if it’s not clear!).

Leave a Comment