PHP 101: Basic Form Validation

bengreenberg profile image Ben Greenberg Originally published at Medium on ・4 min read

Picture courtesy of Public Domain Pictures

When thinking of popular web technologies nowadays you may not first think of PHP. What first comes to mind is probably Javascript or Python, both of which are powerful programming languages. Yet, PHP still plays a very important role on the web both for new applications and as the language for many existing codebases you might encounter. In fact, in the 2017 Stack Overflow developer survey, PHP came in 6th in popularity right behind Python by only a few percentage points.

In this new series I will explore some basic functionality with PHP. As PHP is a language for websites and web applications all of these blog posts will center around incorporating PHP into a web project for increased functionality and dynamism. The first topic we’ll discuss is using PHP to perform some basic form validation.

Form validation is an essential part of web development. Rule #1 in web development is never trust the user. Now that is not to say that every user your project encounters is looking to commit a malicious act. Nonetheless, it is true that every user can make a mistake. Every user can select one item when they meant the other or forget to include information where it’s required and much more. If you don’t want your users to send out incoming missile alerts accidentally then form validation is critical.

Let’s create a form that we’ll work with:

<form action="form_submit.php" method="post">
  <p>First Name: <input type="text" name="first_name" size="20" maxlength="20">
  <p>Last Name: <input type="text" name="last_name" size="30" maxlength="40">
  <p>Email: <input type="email" name="email" size="40" maxlength="60">
  <p>Current Age: <input type="text" name="age" size="10" maxlength="10">  
  <p><input type="submit" name="submit" value="Submit">

Here we have a simple form that asks users for their first name, last name and email address. In PHP the form action is very important. In this case, the form data will be sent to form_submit.php.

As a refresher, we can access the values of each input through the superglobal variable $_POST, which is an array (if the method had been GET then we would have used the variable $_GET). The index for each item in the array can be accessed with the name provided in the input tag. Thus, $_POST['first_name'] would give us the value for the user’s first name they provided.

We are not going to cover in this article what we might do with the form data. Presumably we are asking users for this information to either gain them access to some restricted part of the application, collect their information to add to a database or verify their identity for some reason. All of those functions and a lot more are easy to accomplish with PHP. We will focus on doing something with the data in future topics, but for now, we just want to perform some simple validations.

The first validation we can perform is to check that the user entered information:

if (isset($_POST['first_name'])) {
  // do something;
} else {
  echo '<p>It looks like you forgot to enter your first name.</p>';

The isset function checks to see if the item has been set. In other words, it will only return true if it contains data and is not NULL. Therefore when we perform a conditional check with isset on $_POST['first_name'] it will only be true if the user filled it out. This does not actually check to see what the user filled it out with, but at least it checks if it was filled out at all.

Alternatively, you could use empty() to check that a form field was not left empty. You would do so like this:

if (empty($_POST['first_name'])) {
  echo '<p>You forgot to enter your first name.</p>';
} else {
  // do something;

In order to make sure that a form only contains numeric data and not letters you can use the is_numeric() function. For example:

if (is_numeric($_POST['age']) {
  // do something;
} else {
  echo '<p>You forgot to enter your age.</p>';

This function can be combined with isset or empty to check that a form entry is both filled out and a number at the same time:

if ((isset($_POST['age'])) && (is_numeric($_POST['age']))) {
  // do something;
} else {
 echo '<p>You forgot to enter your age.</p>';

Once you have verified that a user submitted data and that, for example, the data is a number when you want it to be a number, another helpful tool is trim() which removes all extra white spaces from the beginning and end of a string. So if a user accidentally pressed the space bar one too many times when typing in their last name you’ll get rid of all those with trim. You can use it simply like this: trim($_POST['last_name']). In fact, you could assign the return value of that to another variable for easy reference, perhaps $lastname.

There is a lot more to form validation in PHP, particularly when you begin interacting with a database whether MySQL or otherwise. A common example would be the mysqli_real_escape_string() function that removes special characters for use in a SQL statement.

I hope this article provides a good starting point as you begin to think about incorporating form validation with PHP. As always, the go to resource for all PHP related functions is php.net where you can find documentation on every PHP function and much more. Happy coding!

(As mentioned in the title, this is a "101" level article. There is much more to learn, including the very helpful filter_input() function.)

Posted on by:

bengreenberg profile

Ben Greenberg


Rabbi turned Coder. Second Career Dev taking it one function at a time.


markdown guide

I strongly disagree with this article, unless you're struck on a PHP 4 or 5.1. The modern (and recomended) way to validate user input is through filter_input() function, which has a very nice set of sanitization and validation rules, with no need of isset() or empty() calls.
Another issue IMHO is putting directly vars inside a SQL query: you should use prepared statements, removing any SQL injection possibility alltogether. You can sure use mysqli, but his management of prepared statements is quite clumsy: it's WAY better using PDO, which has a very nice interface. And you gain in portability, if you use standard SQL features you can freely switch database server (e.g.: use MySQL in production and a in-memory SQLite for unit tests).
Said that, there's TONS of validation libraries into the wild, and HUNDREDS of libraries for DB abstraction. And no, I don't believe that you're struggling for performances so much: the overhead of some third part library is surely worth the security gain.


Thanks Franco for your comment, I really appreciate it! I will actually be working on a PHP 4 existing codebase, so it's funny you recognized that. I realize now I should also add a caveat to this post to that effect. I also appreciate the recommendations in regards to PDO.


I'm really sorry for you: it's almost 10 years since PHP 4 reached his end-of-life. Mantaining such an old environment should be forbidden by the United Nations :-D

I'll let you bring that up to a vote in the UN General Assembly! :)