How to validate HTML forms using PHP.

In this guide, we are going to show you how to validate HTML forms using PHP.

Whether you like it or not, forms are a major part of every web developer’s life.

If you think about it, most of what we do is based on receiving and validating data that has been sent to us by the client.

To sum it up, we receive data, we validate it, and then we tell our application how to react.

Example HTML form.

We are going to try and keep this as simple as possible.

Below is an example of a very basic HTML form:

<form method="post" action="this-page.php">
    <label>Name<input type="text" name="name"></label><br>
    <label>Email<input type="text" name="email"></label><br>
    <label>Extra Info<br><textarea name="extra_info"></textarea></label><br>
    <input type="submit" name="submit" value="Submit">
</form>

Note that we have three fields:

  • A mandatory name field.
  • A mandatory email field.
  • An optional “Extra Info” field.

Validating forms with PHP.

In this form, there are four fields that we need to pay attention to.

Their names are “name”, “email”, “extra_info” and “submit.” 

That means that we will be dealing with four POST variables called “name”, “email”, “extra_info” and “submit.”

To figure out whether the user has submitted the form, we can use the following piece of code:

if(isset($_POST['submit'])){
    //Submit button has been pressed.
    echo 'Submit button pressed!';
}

In the above example, the isset function checks to see if a POST variable called “submit” exists. If it does exist, then we presume that the user has submitted the form.

To get the values of our text fields, we can do something like this:

if(isset($_POST['submit'])){
    $name = isset($_POST['name']) ? $_POST['name'] : null;
    $email = isset($_POST['email']) ? $_POST['email'] : null;
    $extraInfo = isset($_POST['extra_info']) ? $_POST['extra_info'] : null;
}

In the above snippet, we are using the ternary operator, which basically equates to:

$variableName = (TRUE OR FALSE CONDITION) ? (IF TRUE, DO THIS) : (IF FALSE, DO THIS)

Without using ternary operators, our code would look something like this:

if(isset($_POST['submit'])){
    $name = null;
    if(isset($_POST['name'])){
        $name = $_POST['name'];
    }
    $email = null;
    if(isset($_POST['email'])){
        $email = $_POST['email'];
    }
    $extraInfo = null;
    if(isset($_POST['extra_info'])){
        $extraInfo = $_POST['extra_info'];
    }
}

Note that we’re using isset because there is no guarantee that these form fields will exist.

If you attempt to access a POST variable that does not exist, it will cause an undefined index warning.

When doing basic form validation with PHP, it can be useful to set up an errors array that will hold any UI errors that you want to display to the end user.

For example:

//Create an empty array.
$errors = array(); 

//If our form has been submitted.
if(isset($_POST['submit'])){
    //Validate our fields and add errors to the $errors array.
}

As you can see, $errors is an empty array. It will only contain items if the user has made a mistake.

If the user does fill out the form correctly, then our $errors array will be empty. If the array is not empty, then we can presume that the user has entered an incorrect value:

//Setup an empty array.
$errors = array(); 

//If our form has been submitted.
if(isset($_POST['submit'])){

    //Get the values of our form fields.
    $name = isset($_POST['name']) ? $_POST['name'] : null;
    $email = isset($_POST['email']) ? $_POST['email'] : null;
    $extraInfo = isset($_POST['extra_info']) ? $_POST['extra_info'] : null;

    //Check the name and make sure that it isn't a blank/empty string.
    if(strlen(trim($name)) === 0){
        //Blank string, add error to $errors array.
        $errors[] = "You must enter your name!";
    }
    //Make sure that the email address is valid.
    if(!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        //$email is not a valid email. Add error to $errors array.
        $errors[] = "That is not a valid email address!";
    }
}

In the above example, you can see that UI errors are added to the $errors array if the user enters a blank/empty name or an invalid email address.

We can use this array to our advantage:

//Setup an empty array.
$errors = array(); 

//If our form has been submitted.
if(isset($_POST['submit'])){

    //Get the values of our form fields.
    $name = isset($_POST['name']) ? $_POST['name'] : null;
    $email = isset($_POST['email']) ? $_POST['email'] : null;
    $extraInfo = isset($_POST['extra_info']) ? $_POST['extra_info'] : null;

    //Check the name and make sure that it isn't a blank/empty string.
    if(strlen(trim($name)) === 0){
        //Blank string, add error to $errors array.
        $errors[] = "You must enter your name!";
    }
    //Make sure that the email address is valid.
    if(!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        //$email is not a valid email. Add error to $errors array.
        $errors[] = "That is not a valid email address!";
    }

    //If our $errors array is empty, we can assume that everything went fine.
    if(empty($errors)){
        //Send email or insert data into database.
    }
}

If you look at the code above, you can see that the form is only processed IF the $errors array is empty. Otherwise, the form data is discarded.

Displaying errors to the user.

Finally, how do we display form errors to the user?

<?php 
if(!empty($errors)){ 
    echo '<h1>Error(s)!</h1>';
    foreach($errors as $errorMessage){
        echo $errorMessage . '<br>';
    }
} 
?>

Basically, if the $errors array isn’t empty, then it means that the form didn’t validate properly.