Examples

Contact Form Example [$_POST]
Example Using Table (2 Columns) [$_POST]
Example Using Table (4 Columns) [$_POST]
Example Using Table (2 Columns) [$_GET]
Example Using Paragraphs [$_POST]
Example File Upload / Multiple Uploads

Download

You can download the classes and example files, including this one... in a zip file.

Download
 

About the Class

The class has been written to automatically handle the processing and validation of both POST and GET forms.
You can define what type validation is required from the options already available, or you could easily add new ones, or improve on the existing ones. The included contact form example requires the use of a CAPTCHA... you can define your own, or download the one I have developed. See "defining elements" for more information.

The basic idea behind the form handler class was that you should only define the elements once in your page. And then have just one IF statement checking whether the processing was successful. The class takes care of everything else, like handling and checking values, as well as redirecting the page to get rid of the nasty post variables.

More Information >>

Also included is a class handling the layouts of the form elements, enabling you to organise your form in paragraphs, or tables (2 or 4 columns) as shown in the examples. The class also indents the outputted code properly for easier source code inspection.
The out putted code is valid XHTML according to tthe W3C standards.

The class will also take care of your uploads, automatically checking the files agains the max files size set in the form... or the against the allowed mime types.
The uploads will automatically be moved to the defined upload target directory, and the function returns the path and filename to the uploaded file.
When uploading multiple files, the multiple upload method returns an array of path to the moved files.

You should have a look at the source code of the included example files, to familiarise yourself with the structure you should adhere to.
These example will cover most of the different options you can set withing the class.
To learn more about the methods, and to find out how to extend the functionality, please see the notes below.


HIDE
Comments or praise? -> Contact

Usage

To use the class, you include the class_FormHandler.php and create a new instance of FormHandler.
You then setup the fields you want to include in your form, as well as the options for formatting if required.
After that, you call the method "processForm()" and if process is ok... then you do what you want (send the email... insert into database... etc)... else print out the form.

Here is a simple example:
<?php
@require("classes/class_FormHandler.php");
try {
    
$form = new FormHandler(); // create new form instance

    // SETUP YOUR FORM FIELDS HERE
    
$email $form->createInput("email","email");
    
$form->createSubmit("Submit");
    
    
// then process the form
    
$process $form->processForm();
    if(
$process === "Submit") {
        
// FORM PROCESSING (IF ALL OK)
        // do your stuff here
        
echo $email;

    } else { // display the form
        echo 
$process;    
    }

} catch( 
Exception $e ) {
    echo 
'<h3>Error</h3><p>'.$e->getMessage().'</p>';
//-- ends catch block
?>

Additional Information (multiple submit buttons)

If you are using multiple submit buttons (see defining elements: SUBMIT), then to process the form differently depending on the submit button clicked, you can simply extend the above example.
You will need to use the createSubmitMultiple() method and then use addiditonal "else if" statements to check the value of the $process.
As you will notice, $process returns either the form, the form with errors, or the value of the submit button clicked, if all has been processed ok.
<?php
@require("classes/class_FormHandler.php");
try {
    
$form = new FormHandler(); // create new form instance

    // SETUP YOUR FORM FIELDS HERE
    
$email $form->createInput("email","email");
    
$form->createSubmitMultiple( array("Update","Delete") );
    
    
// then process the form
    
$process $form->processForm();
    if(
$process === "Update") {
        
// do your Update processing here
        
echo $email;
    } else if(
$process === "Delete") {
        
// do your Delete processing here
        
echo $email;
    } else { 
// display the form
        
echo $process;    
    }

} catch( 
Exception $e ) {
    echo 
'<h3>Error</h3><p>'.$e->getMessage().'</p>';
//-- ends catch block
?>


HIDE
 

+ Expand All

FORM SETUP

Change Default Form ACTION

The action of the form by default is itself, so you DO NOT need to set this (this is the way the form works normally).
If, however, you want to do something different with it you may change it like this:
Default:
$form->setFormAction($_SERVER['PHP_SELF']);
Your own stuff:
$form->setFormAction("process.php");


HIDE

Change Default Form METHOD

The method of the form by default is "post", so you DO NOT need to set this if you want to use "post".
If, however, you want to do use "get", then set it like this:
$form->setFormMethod("get");


HIDE

Set Form ID

If you wish to use an ID for the Form, you can set it with the following method:
$form->setFormID("formid");


HIDE

Set Form NAME

Set the form name like this:
$form->setFormName("MyForm");

name = cdata
This attribute names the element so that it may be referred to from style sheets or scripts. Note. This attribute has been included for backwards compatibility. Applications should use the id attribute to identify elements.


HIDE

Other Form Attributes (enctype,accept,onsubmit,onreset,accept-charset)

All of the following methods take only one variable which will be used in constructing the form.
This can be either simple text... list of items... or javascript... function... etc... depending on the attribute.
$form->setEnctype("multipart/form-data");
$form->setAccept("");
$form->setOnSubmit("");
$form->setOnReset("");
$form->setAcceptCharset("");
enctype = content-type
This attribute specifies the content type used to submit the form to the server (when the value of method is "post"). The default value for this attribute is "application/x-www-form-urlencoded". The value "multipart/form-data" should be used in combination with the INPUT element, type="file".

accept-charset = charset list
This attribute specifies the list of character encodings for input data that is accepted by the server processing this form. The value is a space- and/or comma-delimited list of charset values. The client must interpret this list as an exclusive-or list, i.e., the server is able to accept any single character encoding per entity received.
The default value for this attribute is the reserved string "UNKNOWN". User agents may interpret this value as the character encoding that was used to transmit the document containing this FORM element.

accept = content-type-list
This attribute specifies a comma-separated list of content types that a server processing this form will handle correctly. User agents may use this information to filter out non-conforming files when prompting a user to select files to be sent to the server (cf. the INPUT element when type="file").


HIDE

Check for Allowed Hosts

This feature allows you to check the referer and compare it to the values you have set up in the array.
If the domain is not in this array, the form will not be processed.
(only use "localhost" for your testing.)
$form->checkAllowedHosts( array( "localhost" ) );


HIDE

Use Fieldset and Set Legend for Form

If you want to use a fieldset and set a legend for the form, you can do it as follows:
$form->layout->setFieldset(true);
$form->layout->setFieldsetLegend("My Form Class Test");


HIDE

checkdnsrr (validate email domain)

If you want to use this option, use the method below to activate it.
This will only be aplicable to input fields, that have the "check" parameter defined as "email" (in which case normal email pattern matching is carried out anyway)
$form->setCheckDNSRR(true);
If you activate this option, the script will look up the host and validate it.

HIDE

Allowed MIME types

If you want to limit the types of files that can be uploaded through the form, use the method below.
You will need to create an array of allowed MIME types (as in the example below).. and then call the method to activate the option.
$allowed_uploads = array(
	'image/pjpeg'=>'jpg',
	'image/jpeg'=>'jpg',
	'image/gif'=>'gif',
	'image/x-png'=>'png'
	);
$form->setAllowedMIME( $allowed_uploads );	
When you activate this option... any file upload will be checked... and not processed, if MIME type is not in the array.

HIDE

Defining "disabled", "readonly", "tabindex", "accesskey", etc...

Most of the elements allow you to pass a string (called attrib in the function) to them.
This string will be added inside the the element tag without any validation.
So, if you decide to use this, you must yourself take care that it is xhtml compliant and that it works correctly.
This value is always the last value in the function to be passed, if you need to use this, you will need to set all the other optional stuff too.
You can pass several things in this at once if you wish.

for example: "disabled='disabled' readonly='readonly' maxlength='10' or what ever.

Some of the events commonly attached to form elements are, for example:
disabled, readonly, maxlength, tabindex, accesskey, accept... See xhtml documentation for full list and usage.

HIDE

Defining your own javascript for elements

Most of the elements allow you to pass a string (called attrib in the function) to them.
This string will be added inside the the element tag without any validation.
So, if you decide to use this, you must yourself take care that it is xhtml compliant and that it works correctly.
This value is always the last value in the function to be passed, if you need to use this, you will need to set all the other optional stuff too.
You can pass several things in this at once if you wish.

for example: "onfocus='javascript:function1();' onblur='javascript:function2();'"

Some of the events commonly attached to form elements are, for example:
onfocus, onblur, onselect, onchange, onclick, ondblclick, onmousedown, onmouseup, onmouseover, onmousemove, onmouseout, onkeypress, onkeydown, onkeyup

HIDE

Defining ELEMENTS

INPUT

Following values can be passed to this create method:
NAME, CHECK, REQUIRED, Size, LABEL, VALUE, ATTRIBUTES
Only Name is required for basic functionality
// INPUT VARIABLES -> NAME, CHECK, REQUIRED, Size, LABEL, VALUE, ATTRIBUTES
$name = $form->createInput("name","string",true,10,"Your Name",	"");

$email = $form->createInput("email","email");

$phone = $form->createInput("phone","phone",false);
Name -- always needed (used as id and name, as well as label if none defined)
Check -- Type of checking to be performed on this input ("string,"email","phone","captcha")
Required -- If the field is required to be filled
Size -- size of input field
Label -- Define a label to be displayed (else label = Name)
Value -- Prefill the input with a value
---------------
Attributes = Here you can pass in any setup you want (not validated - XHTML compliance not checked)
for example: "onchange='javascript:function()'" or anynything else applicable to the element
This is always the last value, and is not needed unless you want to add extra functionality.


HIDE

SELECT

Following values can be passed to this create method:
NAME, LABEL, SELECTED, OPTIONS, ATTRIBUTES
Only Name And Options are required for basic functionality
// SELECT VARIABLES -> NAME, LABEL, SELECTED, OPTIONS, ATTRIBUTES
$usetype = $form->createSelect(	"usetype","","",array("Commercial","Private") );
You can also use arrays of arrays to define option groups with labels:
$options = array (
    "Group 1"  => array( "option 1", "option 2", "option 3" ),
    "Group 2" => array( "option 4", "option 5","option 6" ),
    "Group 3"   => array( "option 7", "option 8", "option 9" )
);
$options = $form->createSelect(	"options","Option Groups","",$options );
Name -- always needed (used as id and name, as well as label if none defined)
Label -- Define a label to be displayed (else label = Name)
Selected -- Preselected value
Options -- Array() of options to include in the select
---------------
Attributes = Here you can pass in any setup you want (not validated - XHTML compliance not checked)
for example: "onchange='javascript:function()'" or anynything else applicable to the element
This is always the last value, and is not needed unless you want to add extra functionality.


HIDE

SELECT (BOOLEAN)

Following values can be passed to this create method:
NAME, LABEL, SELECTED, ATTRIBUTES
Only Name is required for basic functionality
// BOOLEAN VARIABLES ->	NAME, LABEL, SELECTED, ATTRIBUTES
$subscribe = $form->createBoolean("subscribe","Receive Newsletter", 1);
Name -- always needed (used as id and name, as well as label if none defined)
Label -- Define a label to be displayed (else label = Name)
Selected -- Preselected value
---------------
Attributes = Here you can pass in any setup you want (not validated - XHTML compliance not checked)
for example: "onchange='javascript:function()'" or anynything else applicable to the element
This is always the last value, and is not needed unless you want to add extra functionality.


HIDE

SELECT (NUM)

Following values can be passed to this create method:
NAME, FROM, TO, INCR, SELECT, LABEL, ATTRIBUTES
Select and Label are Optional
// SELECT NUM -> NAME, FROM, TO, INCR, SELECT, LABEL, ATTRIBUTES
$licenses = $form->createSelectNum("licenses",1,10,1,2,"Licenses Required");
Name -- always needed (used as id and name, as well as label if none defined)
From -- Start from number
To -- Up to number
Incr -- in increments of
Select -- Preselected value
Label -- Define a label to be displayed (else label = Name)
---------------
Attributes = Here you can pass in any setup you want (not validated - XHTML compliance not checked)
for example: "onchange='javascript:function()'" or anynything else applicable to the element
This is always the last value, and is not needed unless you want to add extra functionality.


HIDE

SELECT (MULTIPLE)

Following values can be passed to this create method:
NAME, LABEL, SIZE, OPTIONS, ATTRIBUTES
// SELECT MULTIPLE -> NAME, LABEL, SIZE, OPTIONS, REQUIRED, ATTRIBUTES
$lang = $form->createSelectMultiple("languages","",3,array("PHP","Ruby","Java","C++"),false );
Name -- always needed (used as id and name, as well as label if none defined)
Label -- Define a label to be displayed (else label = Name)
Size -- size of input field (shown rows height)
Options -- Array() of options to include in the select
Required -- define if the element is required (true or false)
---------------
Attributes = Here you can pass in any setup you want (not validated - XHTML compliance not checked)
for example: "onchange='javascript:function()'" or anynything else applicable to the element
This is always the last value, and is not needed unless you want to add extra functionality.


HIDE

TEXTAREA

Following values can be passed to this create method:
NAME, COLS, ROWS, REQUIRED, CONTENT, LABEL, ATTRIBUTES
Only Name is required for basic functionality
// TEXTAREA -> NAME, COLS, ROWS, REQUIRED, CONTENT, LABEL, ATTRIBUTES
$info = $form->createTextarea("info",30,3,false,$info_content,"Additional Information");
Name -- always needed (used as id and name, as well as label if none defined)
Cols -- textarea columns size
Rows -- textarea rows size
Required -- If the field is required to be filled
Content -- Prefilled value
Label -- Define a label to be displayed (else label = Name)
---------------
Attributes = Here you can pass in any setup you want (not validated - XHTML compliance not checked)
for example: "onchange='javascript:function()'" or anynything else applicable to the element
This is always the last value, and is not needed unless you want to add extra functionality.


HIDE

RADIO

Following values can be passed to this create method:
NAME, REQUIRED, LABEL, SELECTED, ARRAY, ATTRIBUTES
Only Name and Array are required for basic functionality
// RADIO BUTTONS -> NAME, REQUIRED, LABEL, SELECTED, ARRAY, ATTRIBUTES
$package = $form->createRadio("package",false,"","",array("Package 1","Package 2","Package 3") );
Name -- always needed (used as id and name, as well as label if none defined)
Required -- If the field is required to be filled
Label -- Define a label to be displayed (else label = Name)
Selected -- Preselected value
Array -- Array() of options to include in the select
---------------
Attributes = Here you can pass in any setup you want (not validated - XHTML compliance not checked)
for example: "onchange='javascript:function()'" or anynything else applicable to the element
This is always the last value, and is not needed unless you want to add extra functionality.


HIDE

CHECKBOX

Following values can be passed to this create method:
NAME, SELECTED, LABEL, OPTIONS, ATTRIBUTES
Only Name and Options are required for basic functionality
This Function returns an ARRAY!!
// CHECK BOXES (Returns Array) -> NAME, SELECTED, LABEL, OPTIONS, ATTRIBUTES
$bundle = $form->createCheckboxes("bundle","","Add",array("Bundle 1","Bundle 2","Bundle 3") );
Name -- always needed (used as id and name, as well as label if none defined)
Selected -- Preselected value
Label -- Define a label to be displayed (else label = Name)
Options -- Array() of options to include in the select
---------------
Attributes = Here you can pass in any setup you want (not validated - XHTML compliance not checked)
for example: "onchange='javascript:function()'" or anynything else applicable to the element
This is always the last value, and is not needed unless you want to add extra functionality.


HIDE

HIDDEN

Following values can be passed to this create method:
NAME, VALUE
// HIDDEN FIELDS -> NAME, VALUE	
$maxsize = $form->createHidden("MAX_FILE_SIZE","100000");
Name -- always needed (used as id and name)
Value -- value for the hidden field

If you use the above example, and set "MAX_FILE_SIZE", then that value will also be used in post processing file size validation in PHP

HIDE

FILE UPLOAD

You can either upload a single file... or multiple files.
Remember that you need to set the enctype for the form to use uploads:
$form->setEnctype("multipart/form-data");
You can also set allowed MIME types for files that are uploaded. See Form Setup section.

Upload File uploadFile()
Following values can be passed to this create method:
NAME, LABEL, TARGET, CHMOD, SIZE, ATTRIBUTES
This method returns the path to the moved file in target directory
// FILE UPLOAD -> NAME, LABEL, TARGET, CHMOD, SIZE, ATTRIBUTES
$filename = $form->uploadFile("upload","Choose File","uploads/","644",30);	

Upload Multiple Files uploadMultiple()
Following values can be passed to this create method:
NAME, LABEL, TARGET, CHMOD, SIZE, MAX, ADDLINK, ATTRIBUTES
This method returns an array of paths to the moved files in target directory
// FILE UPLOAD MULTIPLE-> NAME, LABEL, TARGET, CHMOD, SIZE, MAX, ADDLINK, ATTRIBUTES
//$files_array = $form->uploadMultiple("upload","Choose","uploads/","644",5,30,"Add");
Name -- always needed (used as id and name, as well as label if none defined)
Label -- Define a label to be displayed (else label = Name)
Target -- Define the target directory for upload (must end with "/")
Chmod -- Define chmod for moved file, if you wish
Size -- size of inputbox
Max -- Maximum files allowed for uploading multiple mode
Addlink -- label of link to add more fileuploads
---------------
Attributes = Here you can pass in any setup you want (not validated - XHTML compliance not checked)
for example: "onchange='javascript:function()'" or anynything else applicable to the element
This is always the last value, and is not needed unless you want to add extra functionality.


HIDE

CAPTCHA

Following values can be passed to this create method:
NAME, SessionName, LABEL, Size, ImgURL, ATTRIBUTES
You should be able to use this with any normal captcha script...
The current method is setup for my own captcha script.
http://downloads.jv2.net/captcha/
You will see in the examples that the "ImgURL" is defined to start with "/". This is because I have mine in the root. You can of course change the location...
// CAPTCHA -> NAME, SessionName, LABEL, Size, ImgURL, ATTRIBUTES
//$form->createCaptcha("captcha","random","Verification",6,"/captcha/captcha.php?id=".time() );
Name -- always needed (used as id and name, as well as label if none defined)
SessionName -- Name of session variable to store the captcha code
Label -- Define a label to be displayed (else label = Name)
Size -- size of input box
ImgURL -- url of file which generates image and session variable
---------------
Attributes = Here you can pass in any setup you want (not validated - XHTML compliance not checked)
for example: "onchange='javascript:function()'" or anynything else applicable to the element
This is always the last value, and is not needed unless you want to add extra functionality.


HIDE

SUBMIT

There are two methods of creating submit buttons:

For a single button you can use:
$form->createSubmit("Submit");
Or for multiple buttons on the same row, you can use:
$form->createSubmitMultiple( array("Update","Delete") );
Name -- name for submit button
array -- array of names for submit buttons


HIDE

RESET

Following values can be passed to this create method:
NAME
$form->createReset("Reset");
Name -- name for reset button


HIDE

Formatting

Using either Table or P mode

To change the layout of the form... try one of the following:
$form->layout->setUseTable(true);
$form->layout->setUseTable(4);
$form->layout->setUseTable(false);
Accepted Values are (true, false, 2, 4)
If you are using 4... then you will need to change the order you define the form elements, as that affects the order they are inserted in the table.

HIDE

Adding breaks in P mode

If you are using the P mode [setUseTable(false)], then you may want to add breaks between the label and form element (unless you already do that in css by setting display:block for the legend)
$form->layout->setAdd_BR(true);


HIDE

Adding an Empty Row or Paragraph

If you need to add an empty row for formatting (useful for organising things in the 4 column table layout), use the following method:
$form->addEmpty();


HIDE

Radio options displayed inline (flow)

Default for displaying radio options is new line for each.
If you wish to have them displayed next to each other on one line, call the following method, before setting up the radio options.
$form->layout->setRadioInlineFlow(true);


HIDE

Checkbox options displayed inline (flow)

Default for displaying checkbox options is new line for each.
If you wish to have them displayed next to each other on one line, call the following method, before setting up the checkbox options.
$form->layout->setCheckInlineFlow(true);


HIDE

Style / CSS

Set ID and/or Class for Form

If you wish to use an ID or Class for the Form, you can set them with the following methods:
$form->setFormID("formid");
$form->setFormClass("formclass");


HIDE

Set ID and/or Class for Table

If you wish to use an ID or Class for the Table, you can set them with the following methods:
$form->layout->setTableID("tableid");
$form->layout->setTableClass("tableclass");


HIDE

Setting STYLE tags to the table and cells.

If you wish to add style tags to the table and/or cells(columns), you have the following methods available to you:
$form->layout->setStyleTable("style='border:0px;'");
$form->layout->setStyleColumn1("style='text-align:right;vertical-align:top;'");
$form->layout->setStyleColumn2("style='text-align:left;vertical-align:top;'");
$form->layout->setStyleColumn3("style='text-align:right;vertical-align:top;'");
$form->layout->setStyleColumn4("style='text-align:left;vertical-align:top;'");
The values shown are the defaults, you do not need to use these methods unless you want to change them.

HIDE
 
Valid XHTML 1.0 Transitional
class FormHandler()
Copyright © 2007 Joonas Viljanen http://www.jv2design.com
All rights reserved.

Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:

* Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
* Neither the name of the jv2design.com nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.