PHP Form Validation

If you program custom PHP applications, you will often times need to work with a form and require certain form fields. A few real world examples would be a contact form, registration form or signup form. This form validation with PHP tutorial shows you a simple and quick method for creating a form page that handles errors and pre-populates fields if there is an error, and a method for processing the php form and validating the information.
PHP Form Validation Sample Code
This is not meant to be the ultimate php validation example. I would consider this a beginner/intermediate level tutorial that will teach you how to work with PHP forms and PHP form arrays. There are more specific and advanced php form validation techniques that we could implement into this script, but that is not the purpose of this article.
Make sure to put all of the files for this tutorial in the same directory on your server. You can download the php form validation code.
The first thing we will need to create is the html form with some PHP variables. This handles displaying the form and any errors that come up when processing the form, along with pre-populating the form with values they have entered if there is an error.
<?php // index.php ?> <html> <head> <title>PHP Form Processing Example</title> </head> <body> <?=$errorString?> <form action="process.php" method="POST"> Name:*<br /><input type="text" name="Name" value="<?=$Name?>" /><br /><br /> Email:*<br /><input type="text" name="Email" value="<?=$Email?>" /><br /><br /> URL:*<br /><input type="text" name="URL" value="<?=$URL?>" /><br /><br /> Company:<br /><input type="text" name="Company" value="<?=$Company?>" /> <br /><br /> <input type="submit" name="submit" value="Submit Form" /> </form> </body> </html>
PHP Form Processing
I like to keep the PHP form processing and the html form as separate as possible so that it is easier to update.
The next file is where the majority of the PHP code is located. This would be an excellent file to go through if you want to get more familiar with arrays. The comments in the PHP code should help explain what each piece of the code does. The first two arrays at the top of the file are configuration arrays.
Below is the PHP processing page for the above form. You will want to make sure the form action value points to this file.
<?php
// process.php
/*
* Specify the field names that are in the form. This is meant
* for security so that someone can't send whatever they want
* to the form.
*/
$allowedFields = array(
'Name',
'Email',
'URL',
'Company',
);
// Specify the field names that you want to require...
$requiredFields = array(
'Name',
'Email',
'URL',
);
// Loop through the $_POST array, which comes from the form...
$errors = array();
foreach($_POST AS $key => $value)
{
// first need to make sure this is an allowed field
if(in_array($key, $allowedFields))
{
$$key = $value;
// is this a required field?
if(in_array($key, $requiredFields) && $value == '')
{
$errors[] = "The field $key is required.";
}
}
}
// were there any errors?
if(count($errors) > 0)
{
$errorString = '<p>There was an error processing the form.</p>';
$errorString .= '<ul>';
foreach($errors as $error)
{
$errorString .= "<li>$error</li>";
}
$errorString .= '</ul>';
// display the previous form
include 'index.php';
}
else
{
// At this point you can send out an email or do whatever you want
// with the data...
// each allowed form field name is now a php variable that you can access
// display the thank you page
header("Location: thanks.html");
}
And finally, you need the thank you page. In this example, I just use a basic html file.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"> <title>Thanks!</title> </head> <body> <p>Thank you for sending the form!</p> </body> </html>
Click on the PHP Form Validation Sample link to download a zip file of all of the files.
If you have any code you want to add to improve what I’ve done, please share it with us in the comments.
Did you like this article?
Please help us spread the word about this site by tweeting, digging and sharing this article around the web (see the buttons immediately above).
26 Comments or Pings to PHP Form Validation
Trackbacks & Pings
Leave a Comment or a Question
Most Popular
Topics
- PHP Programmer Tips(12)
- Project Management(10)
- WordPress Tips(9)
- Work Smarter(8)
- Sample PHP Code(8)
- Programming Advice(3)
Blogroll

Smart approach indeed!
You have really great taste on catch article titles, even when you are not interested in this topic you push to read it
For me it seems easier and a lot faster to make a multidimensional array and then loop through it to create the input element. To add an entire new field you just have to adjust one line of code instead of 4 like you have to with this code.
That would work, but the problem in going this route is that it is hard to add customizations to each element.
With a simple example like this, is wouldn’t worth it IMO. But it could save a lot of time if you have a huge form to work with…just as long as the form isn’t too complicated.
It is a good concept, and I may come out with doing something like this in CodeIgniter.
Nice ideas. Reminds me of CakePHP’s validation class.
I haven’t specifically used CakePHP’s validation class, but I’ve heard good things. I’ve used other systems, including CodeIgniter, and this technique is not the best way to go when using a framework system like those two.
It is good to go through code like this when you are learning PHP.
Good stuffs although you could add basic data type validation (http://www.php.net/manual/en/ref.ctype.php)
Nice post indeed
Mr, i need concept/sample to Master/Professional validation form to check Email, URL, Name, Character Used, Max / Min and etc i need code form u, because i like your code.
this is a good article, thx for sharing Chris
now i got a little question
how to validate minimum length with this?
like if i want the name to have minimum 3 character
and company have minimum 6 character
sorry for my bad English
In trying your sample code, each form is filled with the ‘value’ assigned in the input tag. This is unusable. Am I missing something?
Thanks!
Also, #errorString is not printing on the page.
Thanks again.
LJ,
It sounds like your server does not have php short tags enabled. In that case, you will need to replace <?= with <?php echo …..also, don’t forget the ending semicolon if you have to do this. This should make the script work on your server.
Let me know if you are still having issues with this. Thanks for your comments!
I’m sorry, replace, exactly what?
I forgot to replace “<” with the html code instead: < . It is now showing up correctly.
This is a nice article and easy to learn something about it.
You have done good job:-)
Thanks a lot..!
this doesn’t work with radiobutton(checked and unchecked)
[code]
$allowedFields = array('radiobutton');
$errors = array();
foreach($_POST AS $key => $value)
{
if(in_array($key, $allowedFields))
{
$$key = $value;
$x .=$key.'';
}
}
echo $x;
[/code]