Simple form validation in PHP

Server-side validation of user input is something you run into once in a while and although it is not an overly complicated subject, there are a couple of gotchas to be aware of.

This blog post examines how to validate a simple form in PHP.
First we need a form. It could look something like this:

View demo

There are a couple of things to notice here.

  • First off, the use of the <label> element which defines a label for an <input> element. It provides a usability improvement for mouse users, as if the user clicks on the text within the <label> element, focus will jump to the <input> element associated with it.
  • Secondly, what the form does when it’s submitted. It simply posts back any values it may have received to itself. This is pretty useless in our case, but demonstrates one of the aforementioned gotchas – any input the user might have entered disappears once the form is submitted! This will annoy users if all correct input is erased when a form is re-rendered owing to a validation error.

So, now let’s make our form do something useful. When the form is submitted I want to access whatever values the user has entered into the ‘first name’ and ‘last name’ fields and display an appropriate greeting. However, if our form is being rendered for the first time, I just want to display the blank form and no greeting.

We can tell if the form is being rendered for the first time by adding the following line of HTML just before the submit button: <input type="hidden" name="process" value="1" />. Then we use the following PHP at the top of our file to check if the process variable is set to ‘1’. This will only be the case if the user has clicked the submit button:

<?php
 if ($_POST['process'] == 1) {
  //do some stuff
 }
 ?>

In the following example I then set the variables $first_name and $last_name to whatever it was the user entered. Check out the PHP.net site for more information on how to retrieve values in a form, submitted with method="post", using the super global $_POST variable.

If both variables are empty, I display the message “Howdy, stranger” otherwise I greet them by name. Also notice the form is called ‘validation example.php’ and the form action has changed accordingly.

View demo

So, now we know how to catch user input, let’s make our ‘last name’ field compulsory and check if the user has filled it out. If he or she hasn’t, we want to display an error message and re-render the form, otherwise we want to display our welcome message.

In the following example I have added a class of error to the error message. This is to be preferred over inline CSS and is more semantic to boot. I have also wrapped the assignment of the $first_name and $last_name variables in a call to the function htmlentities();. This avoids a so-called cross-site scripting attack (XXS), and prevents a potential hacker injecting JavaScript into our web page. Finally, I have added the following attributes to our input boxes value="<?php echo($first_name); ?>" and value="<?php echo($last_name); ?>". This means that whatever value a user enters into either of the input fields is re-rendered in case of a validation error.

You can find out more about XXS here: http://jstiles.com/Blog/How-To-Protect-Your-Site-From-XSS-With-PHP

Upon successful submission, the form could do something a little more complicated than regurgitating the user’s input. For example it could send an email (think contact form), and/or could redirect to another page by setting the headers. For example: header("location: http://hibbard.eu/success");

So, here’s the final code. I hope you find this useful.

View demo

Update (2014.04.11): I was contacted by Gajus, who has written an input validation library called Vlad, which has a simple and intuitive API. I recommend checking this out to see if this is a good fit for your project.

This post currently has 8 responses

  1. calady says:

    the codes are quite good but something is missing especially in names field.it is impossible for a name to numbers but this program allow this.

    • hibbard.eu says:

      Thanks for your comment.
      What I showed was only an example of how validation works.
      It would not be difficult to add this functionality yourself. E.g.

      if(preg_match('#[^a-z]+$#i', $last_name)) {
        echo "Your first name cannot contain numbers or symbols";
      }
  2. Kevin says:

    I’ve been searching for great examples of PHP form entry validation, and your work above is the easiest to follow for beginners and provides exceptional, straightforward examples. You’ve been most helpful to me and I thank you!

    (and I can’t wait to check out the rest of your work too)

  3. bart says:

    hi there

    how to move this php bit outsite of the html ?

  4. Great explanation!Tnx a lot!

  5. darshan says:

    sir this validation not perfect becaus first name in space is alsop allow… so its not ok… space not allowed

    • hibbard.eu says:

      Hi,

      This would be easy to address in your validation code:

      if (preg_match('/\s/',$first_name)){
        // It contains whitespace
      }
  6. alagar says:

    your work is Easiest way for beginners…thanx

Comments are closed!

I'm on Twitter:

Categories