PHP form validation basic example


Validating and sanitizing form data is an important aspect of any web application. It helps to ensure that the data being submitted by the user is correct and safe to use.

In this article, you will learn how to validate and sanitize form data in PHP.

Validating Form Data

Form validation is the process of checking that the data submitted by the user is accurate and complete.

This can be done using a variety of techniques, including:

  • Required fields: Some fields may be required in order to submit the form. These can be done using the isset() or empty() function on the input value.
  • Data types: It is important to check that the data being submitted is the correct data type. For example, if a field is expecting an email address, you can use the filter_var() function with the FILTER_VALIDATE_EMAIL flag to check that the data is a valid email address.
  • Range checks: You may have data that are time-sensitive. For example, you may want to ensure that a birth date is not in the future.
  • Regular expressions: Regular expressions can be used to check that the data being submitted matches a certain pattern. For example, you may want to ensure that a password meets certain complexity requirements.

To validate form data in PHP, you will need to write some code to check the submitted data against your validation requirements.

Example of validating form data

Let’s say you have a form with three fields that have the following requirements:

  • Name - Must be filled and more than 3 letters
  • Email - Must be filled and use a valid email address format
  • Password - Must contain numbers and letters and 8 characters minimum

Suppose the form data is sent using the POST method.

Here is an example of how you might validate the form in PHP:

<?php

// check if the form has been submitted
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // validate the form data
    $errors = [];

    // check that the name field is not empty and is more than 3 letters
    if (empty($_POST["name"]) || strlen($_POST["name"]) < 3) {
        $errors[] = "Name is required and must be more than 3 letters";
    }

    // check that the email field is not empty and is a valid email address
    if (
        empty($_POST["email"]) ||
        !filter_var($_POST["email"], FILTER_VALIDATE_EMAIL)
    ) {
        $errors[] = "Email is required and must be a valid email address";
    }

    // check that the password field contains numbers and letters and is at least 8 characters long
    if (
        !preg_match('/^(?=.*\d)(?=.*[A-Za-z])[0-9A-Za-z]{8,}$/',$_POST["password"])
    ) {
        $errors[] =
            "Password must contain numbers and letters and be at least 8 characters long";
    }

    // if there are no errors, the form data is valid
    if (empty($errors)) {
        // save the data to the database or process it as needed
    } else {
        // there are errors. Print them to the screen
        foreach ($errors as $error) {
            echo $error . '<br>';
        }
    }
}

The PHP code above only runs when a POST request hit the script.

First, we are checking that the name field is not empty and is more than 3 letters. Then, we check that the email field is not empty and is a valid email address.

Finally, check if the password field contains numbers and letters and is at least 8 characters long.

If all of these checks pass, we consider the form data to be valid and can save it to the database or process it as needed.

Sanitizing form data

In addition to validating form data, you also need to sanitize the inputs received from the user to prevent malicious code from entering your application.

Sanitizing data involves removing any potentially harmful or unwanted characters from the data. This can be done using a variety of techniques, including:

  • Escaping output: When processing form data, it is important to escape any special characters to prevent cross-site scripting (XSS) attacks. This can be done using the htmlspecialchars() function.
  • Stripping tags: It is also a good idea to strip any HTML tags from form data to prevent the user from injecting malicious code into your web application. This can be done using the strip_tags() function in PHP.
  • You can also strip unnecessary characters (extra space, tab, newline) from input data using the trim() function.

First, you need to prevent XSS attack by escaping special characters in the form’s action attribute:

<form method="post" 
  action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>"
>

Next, create a custom function to sanitize input as shown below:

function sanitize_input($data) {
    $data = trim($data);
    $data = strip_tags($data);
    $data = htmlspecialchars($data);
    return $data;
}

You can use this function before you validate data as shown below:

<?php

// check if the form has been submitted
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $name = sanitize_input($_POST["name"]);
    $email = sanitize_input($_POST["email"]);
    $password = sanitize_input($_POST["password"]);

    // continue validation process...
}

It is important to sanitize your form data to protect against security vulnerabilities and to ensure that the data being stored and used in your application is safe.

Here’s the complete one page form validation code that you can use:

<html>
<body>
<?php
// check if the form has been submitted
if ($_SERVER["REQUEST_METHOD"] == "POST") {
  $name = sanitize_input($_POST["name"]);
  $email = sanitize_input($_POST["email"]);
  $password = sanitize_input($_POST["password"]);

  // validate the form data
  $errors = [];

  // check that the name field is not empty and is more than 3 letters
  if (empty($_POST["name"]) || strlen($_POST["name"]) < 3) {
    $errors[] = "Name is required and must be more than 3 letters";
  }

  // check that the email field is not empty and is a valid email address
  if (
    empty($_POST["email"]) ||
    !filter_var($_POST["email"], FILTER_VALIDATE_EMAIL)
  ) {
    $errors[] = "Email is required and must be a valid email address";
  }

  // check that the password field contains numbers and letters and is at least 8 characters long
  if (
    !preg_match('/^(?=.*\d)(?=.*[A-Za-z])[0-9A-Za-z]{8,}$/', $_POST["password"])
  ) {
    $errors[] =
      "Password must contain numbers and letters and be at least 8 characters long";
  }

  // if there are no errors, the form data is valid
  if (empty($errors)) {
    // save the data to the database or process it as needed
  } else {
    // there are errors. Print them to the screen
    foreach ($errors as $error) {
      echo $error . "<br>";
    }
  }
}

function sanitize_input($data)
{
  $data = trim($data);
  $data = strip_tags($data);
  $data = htmlspecialchars($data);
  return $data;
}
?>
<form method="post" 
  action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>"
>
Name: <input type="text" name="name"><br>
E-mail: <input type="email" name="email"><br>
Password: <input type="password" name="password"><br>
<input type="submit">
</form>

</body>
</html>

Conclusion

Validating and sanitizing form data is an important aspect of any web application. It helps to ensure that the data being submitted by the user is accurate, complete, and safe to use.

You can validate form data by using functions like empty(), filter_var(), and preg_match().

To sanitize data, you can use functions like trim(), htmlspecialchars(), and strip_tags().

Now you’ve learned how to do form validation in PHP. Great job!

Level up your programming skills

I'm sending out an occasional email with the latest programming tutorials. Drop your email in the box below and I'll send new stuff straight into your inbox!

No spam. Unsubscribe anytime.