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.

Update

I just launched a new article that re-looks at this code and improves it on many different levels. Take a look the Advanced PHP Form Validation article for updated code!

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) &amp;&amp; $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.

79 thoughts on “PHP Form Validation

  1. how to implement this url validation code

    function isValidURL($url)
    {
    return preg_match(‘|^http(s)?://[a-z0-9-]+(.[a-z0-9-]+)*(:[0-9]+)?(/.*)?$|i’, $url);
    }

    Like

  2. Thanks for your code. it works like a charm. ,my form validation is succesfull and instead of a thank you page. i have given a summary page where it shows the values from the form. but these values are not showing.
    can you please help me

    Like

  3. Thank very much it helped me a lot, as you mentioned that now all the allowed variables is now a php variable. can you please help me how to use them.

    Like

  4. -Is there any way to retain values typed when submitting the form so we don’t have to fill the fields all over again ? if yes can you pls show me how in the code?.
    -Is there any extra validation regarding an e-mail address , and how to do it ?

    thank you.

    Like

  5. its a good example but the problem is when we submit the form process.php with single blank field it will flush all other field instead of single one…so plz any one can suggest me how to maintain the data of fields……….thank you

    Like

  6. Great guide, thanks!

    This looks good and straightforward and much better trying to get everything into one unmanageable file Like I have been.

    It looks easy to add extra rules such as email etc and I’ll add some jquery validation to the form also.

    Like

  7. Nice job, keep up the good work, for everyone else that has a problem with this script.. Learn to program, this just an example for learning purposes.. If you can improve the script then do so and don’t complain that it should be this or that way…

    Like

  8. Hello every one

    I am new in programming so I have lots of doubts. However, please let me know regarding “$_POST AS $key => $value” and written values in HTML page.. which we are not specifying in PHP as a variables.. does it take directly a value with names?? $_POST is an array which contains all the input variables but $key and $values we didn’t specify it.. pls let me know whr I am taking it wrong .. Thanks in advance .

    Like

  9. 1. i need a php code to tell my client to download any file in my web page.

    2. I need php form validation code.

    some one should help me out

    Like

Comments are closed.