In previous articles I’ve looked at creating an accessible form using HTML. At the time I mentioned that there were two things we could not do, at least at that stage:

  1. Make a form look pretty (solved with CSS for forms)
  2. Actually do anything with the form information.

We can now solve the latter problem with PHP. But before we send the user’s submitted data anywhere, we must check that they have filled out our form correctly. This is known as “form validation”. (Not to be confused with HTML validation).

On a professional website there are typically two “levels” of form validation. The first uses or HTML5: as the user fills out the form, moving from one field to another, we check what they have entered, providing warnings on the page when entered data does not match the values we expect.

However, since both of these technologies are run client-side, and thus are both insecure and optional (i.e. the user can turn JavaScript off), it is typical to implement a second, server-side check of the data. This is usually done with PHP, and it is this part that we will do first.

There are three steps to validating a form with PHP:

  1. Check that the entered data is correct. If it is, jump to step 3. Otherwise, go to step 2.
  2. Display the form again, preserving any information entered this far and highlighting where errors occur. Allow the user to correct any mistakes and submit the form again, returning to step 1.
  3. When all form data is correct, process it (enter it into a database, send it in an email, etc), and provide some indication to the user that the process is complete.