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. Form Example with Form Validation using PHP…

    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 tutorial shows you a simple and quick metho…

    Like

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

    Like

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

      Like

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

      Like

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

    Like

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

    Like

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

    Like

    • 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!

      Like

  6. this doesn’t work with radiobutton(checked and unchecked)

    $allowedFields = array('radiobutton');
    $errors = array();
    foreach($_POST AS $key =&gt; $value)
    {
        if(in_array($key, $allowedFields))
        {
            $$key = $value;
            $x .=$key.'';
        }
    }
    echo $x;
    

    Like

    • $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]

      Like

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

    Like

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

    John 😦

    Like

    • 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

      Like

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

    Like

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

      Like

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

        Like

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

    Like

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

    Like

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

    Like

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

    Like

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

    Like

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

    Like

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

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

    Like

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

    Like

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

    Like

Comments are closed.