Web20 University

A beginner's guide to PHP HTML Form Validation

Last edited on
Get up to 65% Off Hosting with FREE SSL & FREE Domains!

* Web 2.0 University is supported by it's audience. If you purchase through links on our site, we may earn an affiliate commision.

When users submit forms on your site—whether to sign up for an account, log in, or send a contact message—you need to ensure that the data is valid, secure, and formatted correctly especially if you’re going to be adding this data to a database.

So using PHP to validate HTML forms is a good way to make sure the data the user is providing is as you would expect it to be.

In this post, we’ll explore the simplest ways to validate forms using PHP, cover best practices to ensure clean and secure code, and highlight some popular libraries and packages that can streamline the form validation process.


The Simplest Ways to Validate Forms with PHP

PHP offers a number of basic techniques to validate user input, and it’s important to implement them to avoid issues like incorrect data formatting or potential security threats such as SQL injection and cross-site scripting (XSS).

1. Client-Side vs. Server-Side Validation

  • Client-side validation happens in the user’s browser using JavaScript or HTML5. While helpful for providing quick feedback, client-side validation isn’t foolproof since users can disable it.
  • Server-side validation, which is done using PHP, ensures that validation happens securely, even if client-side validation is bypassed.

For the most secure and reliable results, it’s always best to use server-side validation (PHP) in addition to client-side validation.

2. Validating Form Fields in PHP

Let’s look at a simple PHP form validation example. Suppose we have an HTML form that collects a user’s name and email address:

<form action="process.php" method="POST">
  Name: <input type="text" name="name">
  Email: <input type="email" name="email">
  <input type="submit" value="Submit">
</form>

The corresponding PHP code to validate the form submission could look like this:

<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $name = cleanInput($_POST['name']);
    $email = cleanInput($_POST['email']);
    
    // Validate name
    if (empty($name)) {
        echo "Name is required.";
    } elseif (!preg_match("/^[a-zA-Z-' ]*$/", $name)) {
        echo "Only letters and white space allowed in the name.";
    }

    // Validate email
    if (empty($email)) {
        echo "Email is required.";
    } elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        echo "Invalid email format.";
    }
}

// Function to clean input data
function cleanInput($data) {
    $data = trim($data);
    $data = stripslashes($data);
    $data = htmlspecialchars($data);
    return $data;
}
?>

In this example:

  • cleanInput() is a custom function to sanitize the input by trimming spaces, stripping slashes, and converting special characters to HTML entities.
  • We use filter_var() for validating email format.
  • preg_match() is used to ensure the name contains only valid characters.

This basic setup covers essential validation but can be extended as needed.

Best Practices for Form Validation in PHP

When validating forms in PHP, it’s essential to follow certain best practices to maintain security, performance, and usability.

1. Sanitize All User Input

Always sanitize any data you receive from users. This prevents malicious users from injecting harmful code into your site. The htmlspecialchars() function is commonly used to prevent XSS attacks by escaping HTML characters.

2. Validate on Both Client and Server

While PHP handles server-side validation, combining it with JavaScript-based client-side validation enhances user experience by giving instant feedback, even before the form is submitted.

3. Use Built-In PHP Functions

PHP provides several built-in functions to validate and sanitize different types of data:

  • filter_var() can validate URLs, emails, and IP addresses.
  • is_numeric() can check if a value is numeric.
  • ctype_alnum() checks if a string contains only alphanumeric characters.

4. Handle Error Messages Properly

Provide clear error messages to users without exposing too much information that could aid an attacker. For example, instead of saying “Invalid password,” you could say “Password must be at least 8 characters long and include a number.”

5. Cross-Site Request Forgery (CSRF) Protection

Implementing CSRF protection tokens ensures that only forms submitted from your site can be processed, making it harder for malicious actors to submit data on behalf of users.

6. Secure Data Storage

Once data is validated, ensure it’s stored securely, especially sensitive information like passwords, which should be hashed using secure algorithms (e.g., password_hash()).


Libraries and Packages for PHP Form Validation

While you can validate forms manually as shown above, using a library can save time and effort. Several popular PHP form validation libraries exist to handle this task more efficiently.

1. Respect/Validation

The Respect/Validation library is one of the most popular and robust validation libraries for PHP. It offers an expressive and readable syntax for validating form inputs.

Here’s an example of how to use it:

use Respect\Validation\Validator as v;

$nameValidator = v::alnum()->length(1, 50);
$emailValidator = v::email();

$name = $_POST['name'];
$email = $_POST['email'];

if (!$nameValidator->validate($name)) {
    echo "Invalid name.";
}

if (!$emailValidator->validate($email)) {
    echo "Invalid email.";
}

Respect/Validation supports a wide range of rules, from basic string validation to more complex rules for URLs, domains, and arrays.

2. Symfony Validator

The Symfony Validator component is a versatile tool often used in the Symfony framework, but it can be used independently for PHP validation tasks. It allows you to apply constraints to your form data in a clean, reusable way.

use Symfony\Component\Validator\Validation;
use Symfony\Component\Validator\Constraints as Assert;

$validator = Validation::createValidator();
$violations = $validator->validate($_POST['email'], [
    new Assert\Email(),
    new Assert\NotBlank(),
]);

if (count($violations) > 0) {
    foreach ($violations as $violation) {
        echo $violation->getMessage();
    }
}

3. Valitron

Valitron is a lightweight, simple PHP validation library that is easy to use and doesn’t have any external dependencies. It works by defining validation rules for each field:

use Valitron\Validator;

$v = new Validator($_POST);
$v->rule('required', ['name', 'email']);
$v->rule('email', 'email');
$v->rule('alpha', 'name');

if ($v->validate()) {
    echo "Form data is valid!";
} else {
    print_r($v->errors());
}

Valitron is perfect for smaller projects where you want a simple, no-fuss solution.


Conclusion

Validating forms with PHP is crucial for ensuring data accuracy, security, and a smooth user experience. Whether you’re validating input manually or using a library like Respect/Validation or Symfony Validator, it’s important to follow best practices like sanitizing inputs, handling errors effectively, and securing the form submission process.

By understanding the basics of PHP form validation and leveraging existing libraries, you can build safer, more reliable web applications that provide a positive experience for users and protect your backend systems from malicious activity.

Get up to 65% Off Hosting with FREE SSL & FREE Domains!