How to perform back-end validation in PHP

Overview

In this shot, we will learn to perform back-end validation in PHP.

Let’s imagine that we built a web application and are ready to ship it to the world. We should think twice before doing so.

First, is our front-end secured? We must ensure that we use the latest HTML 5 features to protect our form inputs, JavaScript for a better UX when filling the form, and so on.

We can learn more about front-end validation here.

Next, is our back-end also protected? If not, this shot is for you.

Why back-end validation?

Why do we need back-end validation when our front-end is already robust? Because the front-end validation is easy to bypass. As a rule of thumb, the server should never trust the data it receives from the client (browser).

We can bypass the front-end validation when:

  • A malicious user turns off JavaScript on their browser.
  • A middleman attack changes data just after the request is submitted by a user, but before it is received by the server.

Prepared statements

We need prepared statements if our application relies on user inputs to perform database tasks:

<?php
function add_project($title, $category)
{
try {
global $connection;
$sql = 'INSERT INTO projects(title, category) VALUES(?, ?)';
$statement = $connection->prepare($sql);
$new_project = array($title, $category);
$affectedLines = $statement->execute($new_project);
return $affectedLines;
} catch (PDOException $exception) {
echo $sql . "<br>" . $exception->getMessage();
exit;
}
}

Explanation

In the above code:

  1. Line 7: We notice that there is no untrusted data embedded in our SQL statement. It is instead replaced by placeholders (?).
  2. Line 9: We prepare the statement, i.e., create an SQL statement template and send it to the database server.
  3. Line 12: We execute, during which the parameter values are sent to the server.

Note: You can learn more about the prepared statement from this shot.

Filter data (sanitizing and validating)

Web applications rely on a big part of external data, and by default, this data should be seen as unsafe. Therefore, failing to apply PHP filtering may lead to security issues.

To filter input, PHP provides us with a built-in function called filter_var():

  • Sanitize: This removes any bad or illegal characters from the data.
  • Validate: This tests whether data is in a valid format.

Let’s see some examples of the filter_var() function.

The filter_var() function accepts two parameters:

  • The variable to filter.
  • The filter to use.

Filter string and integer

The sample code for sanitization of string str is given below:

<?php
// sanitize a string
$str = "<h1>Hello World!</h1>";
$newStr = filter_var($str, FILTER_SANITIZE_STRING);
echo $newStr;

The sample code for sanitization of integer int is given below:

<?php
// validate an integer
$int = '2';
echo (filter_var($int, FILTER_VALIDATE_INT))
? "This is an integer."
: "This is not an integer.";

The above code works as intended, except when $int = 0.

We can do a zero check to work around it:

<?php
// validate an integer
$int = '0';
$filtered = filter_var($int, FILTER_VALIDATE_INT);
echo ($filtered || $filtered === 0)
? "This is an integer."
: "This is not an integer.";

The output shows that it is not working for the case where int=0.

Validate an email

<?php
$email = 'sarah.lifaefi@kavira.com';
// Remove all illegal symbols from email
$email = filter_var($email, FILTER_SANITIZE_EMAIL);
// Validate e-mail: yes, it's a properly formatted e-mail @
echo (filter_var($email, FILTER_VALIDATE_EMAIL))
? "This is a valid e-mail address."
: "This is not a valid e-mail address.";

Wrap up

This shot explained that the front-end validation alone is not enough in web applications. We should do it with back-end validation to make them fully secure. We should also remember:

  • Sanitization (filter_var($var, FILTER_SANITIZE_*)) is to clean the illegal character out of data
  • Validation (filter_var($var, FILTER_VALIDATE_*)) is to confirm that the data is a valid format.
  • Prepared statements are for database operations that rely on external inputs.

Free Resources