PHP Form Validation

Written by Chris Roane
phpformexample

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) && $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?

Enter your email address below to get notified when the site is updated. Or you can always subscribe to the RSS Feed.

Please help us spread the word about this site by tweeting, digging and sharing this article around the web (see the buttons immediately above).

Thursday, February 25th, 2010

79 Comments or Pings to PHP Form Validation

  • Benoa says:

    Smart approach indeed!

  • kaizoku says:

    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.

    • Chris Roane says:

      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.

  • Abhisek says:

    Nice ideas. Reminds me of CakePHP’s validation class. ;-)

    • Chris Roane says:

      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. :)

    • neelu says:

      yes u r true sir gi

  • Musa says:

    Good stuffs although you could add basic data type validation (http://www.php.net/manual/en/ref.ctype.php)

    Nice post indeed

  • indraphpx says:

    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.

  • Ivan says:

    this is a good article, thx for sharing Chris :D

    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 :D

  • LJ says:

    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!

  • LJ says:

    Also, #errorString is not printing on the page.

    Thanks again.

    • Chris Roane says:

      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!

  • This is a nice article and easy to learn something about it.

    You have done good job:-)

    Thanks a lot..!

  • Ivan says:

    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]

    • srinivas says:

      $allowedFields = array(‘radiobutton’);//pass the radiobutton values in array() it may work
      $errors = array();
      foreach($_POST AS $key => $value)
      {
      if(in_array($key, $allowedFields))
      {
      $$key = $value;// is $$key=$value or $key=$value
      $x .=$key.”;
      }
      }
      echo $x;
      [/code]

  • John Simpson says:

    Hello

  • John Simpson says:

    Thanks

  • John Simpson says:

    Sorry, I just realised that this form is actually sending you feedback.

    Well – I’ve only just finished creating my first two websites one of which was actually a design school project site. The school teacher that taught us Dreamweaver CS4 didn’t have the time, or to be honest did not know how to complete a form that functions properly ie: After clicking the “Submit” button I wanted to know why I wasn’t getting any feedback details from the form user, she couldn’t tell me and suggested I search the internet. She couldn’t even tell me that I needed a processing page.

    Well here I am at your very helpful resource site and very grateful to have found some answers, now I will have to try to adapt it for my site. All I have in my site is: Name, email and a Submit button, although I might add a text field.

    warm regards
    John

  • John Simpson says:

    I tried downloading the form validation code but it wouldn’t download, perhaps because I’m using a Mac.

    John :-(

    • ThatGuy says:

      hey i love this tutorial except i dont want it to print “email” or “name” when the feild is incorrect.

      How could i change this:

      $allowedFields = array(
      ‘Name’,
      ‘Email’,
      ‘URL’,
      ‘Company’,
      );

      // Specify the field names that you want to require…
      $requiredFields = array(
      ‘Name’,
      ‘Email’,
      ‘URL’,
      );

      To show for example: “Name is incorrect”.

      Thanks in advance

  • John Simpson says:

    My apologies, I made a slight error typing my email address, the correct spelling is saysumat@tpg.com.au

    thanks
    John

  • Mike says:

    Hello Chris

    Non of this code is working for me?? I just don’t get it! for example the index.php renders with the php variables and code appearing in the form fields – how is that supposed to work if the user can see the php code in the form fields. What am I missing here?

    • Mike says:

      Ok please ignore this. I got the form working by using <?echo…

      but he validation does not appear to work – The validation does not fail if the email field is left blank.

      • Chris Roane says:

        It sounds like your server may not allow php short tags. You may need to replace the php printing code with <?php echo $Name; ?> (as an example). If this doesn’t make sense, than you probably need to spend more time learning the basics of PHP.

  • Mike says:

    Got it working now! Thanks for the code

  • juango says:

    Hello Chris, I uploaded the thanks.html, process.php and index.php to my server then I entered all the information that index.php was asking me for then I clicked on Submit Form and received a

    “Thank you for sending the form!” …
    Can you clear something for me, Where did I send the information I entered in the index.php form to?

    Thanks…..Juango

  • Chris Roane says:

    As it mentions in a comment in the code, you can add code to send an email. The code does not actually send an email though.

    This example shows you how to validate form fields through PHP.

  • Mike says:

    Hi Chris,

    nice approach is almost what i need, I did change some of your code from the place you did put it trying to make appear the error inside the input text fields but I get Name!Email!, let me show you so you can have a better idea what i’m doing.

    ————-
    process.php

    $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[] = “$key !”;
    }
    }
    }

    if(count($errors) > 0)
    {
    $errorString = ”;
    foreach($errors as $error)
    {
    $errorString .= “$error”;
    }

    include ‘index.php’;
    }
    else
    {
    header(“Location: thanks.html”);
    }

    ———-
    index.php

    Name:*
    <input type="text" name="Name" value="” />
    Email:*
    <input type="text" name="Email" value="” />

    can you help me to done what i’m trying to do please??? I have to said that i’m new to php, that’s way I asking you help

    thanks

  • yogeesh rao says:

    validation code for text box if i enter number,symbols other than characters(a-z,A-Z) in PHP Form.

  • cialis says:

    After examine a couple of of the weblog posts on your web site now, and I actually like your way of blogging. I bookmarked it to my bookmark web site record and shall be checking back soon. Pls try my web page as well and let me know what you think.

  • Rahul Singh says:

    Thanks for The tips by given all by you i am implementing all

  • Ariffin says:

    Great Stuff! Thanks… :)

  • saravanan says:

    i need validation form am nt geting correctly

  • MHodges says:

    Thanks for this information.

    I am using it now, but I have an issue where the form is still sent even though I have it telling the user that the form must be filled. I am sure I am the problem, as my php skill set is very limited. Do you think you could advide me?

  • pw says:

    Knocked my socks off with !

  • s k sharma says:

    Nice work thanks a lot

  • Amereservant says:

    The problem with checking for “allowed” fields is when trying to add additional fields via Javascript. For example, say I have a phone number field and want to allow the user to add additional numbers, the field wouldn’t first be registered and therefore ignored.

    I ran into this problem after writing a form class that registered the fields, created the input field syntax, added any attributes, then validated the fields when the form is submitted.

    The other catch to this form validation is that there’s no sort of data validation, only checking if the fields are empty or not if they are required meaning bogus data such as a single letter/number could be entered for any of the parameters and it would pass.
    Just stating that for anyone looking for a quick snippet to try validating forms with and not knowing PHP.

  • gaurav garg says:

    Very Nice script for the begineers :)

  • ThatGuy says:

    $allowedFields = array(
    ‘Name’,
    ‘Email’,
    ‘URL’,
    ‘Company’,
    );

    // Specify the field names that you want to require…
    $requiredFields = array(
    ‘Name’,
    ‘Email’,
    ‘URL’,
    );

  • i visit this site when i need some php script for http://www.packersmoversinindia.in and i found good script. now i implement this script

    thanks

  • Chris says:

    How can I display the message error “The field Name is required” alongside the Name box ? Thank you!

  • jirik says:

    thanks a lot
    with my php knowledge I would never figure out how to write this (or maybe I would but with 100x longer source code ;)

  • bhagyashree says:

    greate

  • bhagyashree says:

    but i want to make a form like

    registration.html
    *username,*email,*gender,*address,*city,country,
    *password,*confirm_password
    *=required fields in red color when make error

    login.php
    email,password
    if this fields are in the database then open the next file(welcome_newpg.php)if no match then make error email and password are not valid(red color), otherwise create new account and then login

    welcome_newpg.php
    welcome username
    link of logout(logout.php)

    logout.php
    when user click logout then open the login.php

    can you help me to make this program please?

  • MNVOH says:

    thanks, good tutorial, but it would be great if you had included email validation or something like that.

  • fifi says:

    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);
    }

  • amjad says:

    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

  • rasin says:

    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.

  • yuvakumar says:

    sfkndsnfdjndn

  • nikachu says:

    Thanks for the tutorial, Chris, it was a huge help :)

  • This is a great article. I was having some trouble with validation but this spells it out perfectlyu!~

  • naim says:

    -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.

  • Feroz says:

    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

  • chakotha says:

    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.

  • Artofwork says:

    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…

  • Rajesh Jain says:

    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 .

  • Jonade says:

    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

  • Ed Bob says:

    Nice script. I need help validating more that one form pls.

  • Balu Mahesh says:

    Very Use ful…
    thanks….

Trackbacks & Pings