skip navigation

www.Hilands.com


Content:: PHP Form Process Class

PHP - Form Process Class

Table of Contents

About
The Form Process Class is an class designed to assist the creation of web forms.

The Class will help you parse a simple HTML file, run error checks based on the configuration you provide, return the form with highlighted error messages, and verify if the data submitted is ready for completion.

In total two files will need to be created.
  1. A basic HTML form with two simple text blocks:
    1. One named [error] which will be replaced with an error message or removed if no error exists.
    2. A second named [frmAction] which will fill in the form action section of the html (<form action="[frmAction]" method="post">).
  2. A PHP file which will:
    • Include the Form Process Class file
    • Determine the HTTP referer
    • Check if the webpage is on a secure connection
    • Define the Form Configuration array ($arrFormConf)
    • Instantiate the Form Process Class
    • Check if data has been sent to the form
      • If data has not been sent display the HTML file.
      • If data has been sent validate data based on the configuration you provide and check for custom error processing
        • If Data is invalid, errors were found, reprint the html template with errors highlighted
        • If Data is valid Go to "Final Code Processing" section
The HTML File

Basic HTML form Our example html file shows the [frmAction] block on line 3 and the [errorMsg] block on line 4. The rest are examples of form elements like : text, password, textarea, select, checkbox, radio and submit buttons.
The code below will look like the image to the left when viewed in an HTML browser.

<html>
<body>
<form action="[frmAction]" method="post">
[errorMsg]<br />
Text Field: <input name="text" type="text" value="" /><br />
<br />

Password Field: <input name="password" type="password" value="" /><br />
<br />

Text Area:
<textarea name="textarea" type="textarea"></textarea>
<br />

Select Box: 
<select name="select">
	<option value="option1" selected>Option 1</option>
	<option value="option2">Option 2</option>
	<option value="option3">Option 3</option>
	<option value="option4">Option 4</option>
</select>
<br />

Check Box: <input name="checkbox" type="checkbox" value="checkbox" checked />
<br />

Radio Buttons: <input type="radio" name="radio" value="1"> 1
	<input type="radio" name="radio" value="2"> 2
	<input type="radio" name="radio" value="3"> 3
<br />

<input name="submit" type="submit" value="submit" />
</form>

</body>
</html>
The PHP File
Our first line of code we will include the Form Process Class file.
require ("./form_process.class.inc.php");
I prefer my own custom error message while including the file, you may notice the following in some of the example files.
if (file_exists("./form_process.class.inc.php")) { include ("./form_process.class.inc.php"); } else { echo 'failed to open form_process.class.inc.php'; exit;}
The system checks to see if we have a valid referer. The following will check if a referer is available, if so it will store the string in $strReferer for later use in the error message if needed.
if (array_key_exists('HTTP_REFERER', $_SERVER))
	$strReferer = $_SERVER['HTTP_REFERER'];
else
	$strReferer = "";
We will check to see if we have a secure https connection which will be used for the referer verification.
if (!empty($_SERVER['HTTPS']))
	$strServer = "https://";
else
	$strServer = "http://";
The Form Configuration array will contain the most amount of information in the file. We'll break down the information by the first layer of array keys.
  • formFile - This will be the name of the HTML file that will be processed.
  • validReferer - Is an array of valid http referers. We should only need one, the name of the PHP file. The variables below will generate this filename automatically for us. For certain include files you may need to modify this to every file name that includes such file.
  • fieldText - This is the text related to a form field. Include spaces, html code, etc for better accuracy. If the field fails to validate the text designated below will be wrapped with the errorWrapper data later in the configuration array.
  • fieldError - This is the text that will populate the "field" blocks in the error messages.
  • validation - Is an array containing a sub array with the name of the field followed by the checks that should be done. We can check to see if a field is "required" which means it must contain some type of data, if the field needs to follow proper email formatting.
    We can also set up a match with a sub array of two fields common use would be password fields to ensure the passwords match
  • errorWrapper - Is an array with two keys 0 and 1. The value in key 0 will be added to the beginning of the error string while the value in key 0 will be added to the end of the error string.
  • errorMsgWrapper - Similar to errorWrapper however this will go around the entire set of error messages. This will wrap around the [error] block.
  • errorMsg - Each array key defines the error type, while the value defines the error message.
//----------------------------------------------------------------------------//
// arrFormConf - Form Configurations                                          //
//----------------------------------------------------------------------------//
$arrFormConf = array(
	'formFile' => "form.html",
	'validReferer' => array(
		$strServer.$_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF'],
	),
	'fieldText' => array(
		'text' => 'Text Field:',
		'password' => 'Password Field:',
	),
	'fieldError' => array(
		'text' => 'Text Field',
		'password' => 'Password Field',
	),
	'validation' => array(
		'text' => array(
			'required',
			'email',
		),
		'match' => array(
			'text',
			'password',
		),
	),
	'errorWrapper' => array(
		'0' => "\n".'',
		'1' => "\n"
	),
	'errorMsgWrapper' => array(
		'0' => "\n".'
Error
', '1' => "
\n" ), 'errorMsg' => array( 'referer' => 'Invalid Referer ['.$strReferer.']- You must use the same form provided by the host processing it', 'required' => '[field] is a required field and cannot be blank', 'match' => 'The fields [field-a] and [field-b] do not match.', 'email' => 'The Email address entered is not valid please verify', 'captcha' => 'Captcha text does not match the image, use the reset checkbox to reset the image', ) ); //----------------------------------------------------------------------------// // End arrFormConf - Form Configurations // //----------------------------------------------------------------------------//
Instantiate the Form Process Class
$refForm = new form_process($arrFormConf);
Check if data has been sent to the form
if (array_key_exists('submit', $_REQUEST))
	$boolDataSent = true;
else
	$boolDataSent = false;

if ($boolDataSent)
{
	$refForm->checkReferer();
	$refForm->checkValidation();
	//------------------------------------------------------------------------//
	// Data Valid Enter your Processing Code HERE                             //
	//   Use a simple if statement, if failure add                            //
	//   1. $refForm->boolError = true;                                       //
	//   2. $refForm->strErrorMsg .= "<custom error message><br />\n";        //
	//   if(<check for error>)                                                //
	//   {                                                                    //
	//       $refForm->boolError = true;                                      //
	//       $refForm->strErrorMsg .= "<custom error message><br />\n";       //
	//   }                                                                    //
	//------------------------------------------------------------------------//

	//------------------------------------------------------------------------//
	// End Data Valid Enter your Processing Code HERE                         //
	//------------------------------------------------------------------------//
	if ($refForm->returnErrors())
	{
		$refForm->processInputData();
		echo $refForm->strTemplate;
	}
	else
	{
		//--------------------------------------------------------------------//
		// Final Code Processing Here                                         //
		//--------------------------------------------------------------------//
		echo "data has been submitted!";
		echo "
"; print_r($_REQUEST); echo "
"; //--------------------------------------------------------------------// // End Final Code Processing Here // //--------------------------------------------------------------------// } } else { echo $refForm->strTemplateOrig; }

View Example

form_process.class.inc.20091027.zip
Download 27,585 bytes
8301f164654d60b0f578e7af1b73351c *form_process.class.inc.20091027.zip

Last Modified: 2011-05-23