Basics
Creating a Document
Head and Body Elements
Formatting Text
Creating Lists
Embedding Images
URLs Explained
Linking to Documents
Creating Tables
Forms Form Basics
Input and Textarea
Select Lists
Frames Framesets
The Frame Element
Nested Framesets
Targetting Frames
Inline Frames
Tips and Tricks Meta Tags
Transition Effects
HTML Generators Create a Document
Create a List
Create a Table
HTML
Basics
Implementing CSS
CSS Syntax
Pseudo Classes/Elements
CSS Classes
CSS Properties Font Properties
Color and Background
Text Properties
Border Properties
Margins and Padding
Size and Position
Tips and Tricks Menu Buttons
Special Effects
CSS
Basics
Running a Script
Variables
Expressions and Operators
Objects.Properties.Methods
The Date Object
Strings
Regular Expressions
Defining RegExp Patterns
Branches and Conditions
Loops
Arrays Array Basics
Array Methods
Sorting Arrays

User-Defined Functions
Cookies
Windows
Frames
Tips and Tricks Image Replacement
Using Includes
Form Validation
Debugging
JavaScript
Basics
Creating a Script
Running a Script
Variables
Expressions and Operators
Strings Strings Basics
Strings and Substrings
Replacing Substrings
Regular Expressions
Branches and Conditions
Loops
Arrays Array Basics
Array Functions
Sorting Arrays
User-Defined Functions
Include and Require
Uploading Files
File Functions
Session Variables
Tips and Tricks Page Templates
Form Reply Scripts
Form Validation
JavaScript to PHP
PHP
Basics
Create and Drop
Show and Describe
Insert, Update and Delete
Querying
Join Queries
Functions
Table Locking
PHP/MySQL Functions Accessing a Database
Querying with PHP
Create and Drop with PHP
Insert and Update with PHP
Frequently Used Functions MySQL
Basics
Layout and Navigation
Page Content Style
Web Page Copy
Graphics and Animation
HTML Forms
Accessibility
Legal Requirements
MySQL
PHPBasicsCreating a ScriptRunning a ScriptVariablesExpressions and OperatorsStringsStrings and SubstringsReplacing SubstringsRegular ExpressionsBranches and ConditionsLoopsArraysArray FunctionsSorting ArraysUser-Defined FunctionsInclude and RequireUploading FilesFile FunctionsSession Variables
Recommended Reading
PHP and MySQL web development

programming PHP

PHP cookbook

Home > PHP Tips and Tricks > Form Validationprinter version

PHP Form Validation

It's useful to validate an HTML form using JavaScript before a form is submitted but it shouldn't be considered as a substitute for validating the form on the server.

JavaScript can be interfered with by the user on the client side but not PHP on the server side and this is covered in the tutorial Form Reply Scripts.

If PHP finds an error with the submitted data it needs to redirect the user back to the form.

However, to be useful, the script needs to inform the user which fields are in error as well as ensure that the form still holds the data that the user originally entered.

Using Session Variables

Both these needs can be met using Session Variables.



Both sets of session variables can be written into the HTML form but won't be displayed if no error has been found by the script that handles the form data.

The HTML Form

Below is a simple form that gathers two name/value pairs, name and email, and passes them to form_reply.php when the user clicks the Send button.

The form is standard except for the following additions.

In this example the validation only checks for blank fields and if found will produce one of 3 error messages.



The contact.php page with Session Variables
<?php session_start(); ?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
</head>
<body>
<form action="form_reply.php" method="post">
    Your name:
    <input type="text" size="50" maxlength="75" name="name" value="<?php echo($HTTP_SESSION_VARS["name"]); ?>" >
    <?php echo($HTTP_SESSION_VARS["error_1"]); ?>
    Your email address:
    <input type="text" size="50" maxlength="75" name="email" value="<?php echo($HTTP_SESSION_VARS["email"]); ?>" >
    <?php echo($HTTP_SESSION_VARS["error_2"]); ?>
    <?php echo($HTTP_SESSION_VARS["error_3"]); ?>
    <input type="submit" name="Send">
</form>
<?php session_destroy(); ?>
</body>
</html>


The Form Script

The form script first has to store the form data as session variables to repopulate the form if validation fails.

Next it has to validate each field and if the validation fails, create session variables to hold appropriate error messages.

Finally if error messages have been created then the script should send the user back to the contact.php page - or if not, then go ahead and send the email.

The form_reply.php Script
<?php
session_start();
if (!session_is_registered("name")) session_register("name");
    $HTTP_SESSION_VARS["name"] = $HTTP_POST_VARS["name"];

if (!session_is_registered("email")) session_register("email");
    $HTTP_SESSION_VARS["email"] = $HTTP_POST_VARS["email"];

//Check for blank name and email fields
if ($HTTP_POST_VARS["name"] == "" && $HTTP_POST_VARS["email"] == "")
{
    session_register("error_3");
    $HTTP_SESSION_VARS["error_3"] = "*Both your name and email address are required!";
    header ("location: contact.php");
    exit;
}

//Check for blank name field
if ($HTTP_POST_VARS["name"] == "")
{
    session_register("error_1");
    $HTTP_SESSION_VARS["error_1"] = "*Your name is required!";
    header ("location: contact.php");
    exit;
}

//Check for blank email field
if ($HTTP_POST_VARS["email"] == "")
{
    session_register("error_2");
    $HTTP_SESSION_VARS["error_2"] = "*Your email address is required!";
    header ("location: contact.php");
    exit;
}

// If the script gets to here then forward the data
// Code for sending the email
?>





Privacy | Terms | Contact | Links | Sitemap | RSS Feeds RSS and JavaScript Feeds
©2010 www.webdesignworkmate.co.uk all rights reserved 
Design and Production by smallbizonline website design © 2000-2010
Valid HTML 4.01! Level Double-A conformance icon, W3C-WAI Web Content Accessibility Guidelines 1.0Valid CSS!
Tips and TricksPage TemplatesForm Reply ScriptsPHP Form ValidationForm ValidationJavaScript to PHP
Got any PHP Tips?
Send me your tip and if it's suitable I'll put it on the site, credit it to you and add a link back to your site.