Validating User Input With filter_var()

This function make it easy to validate an email address, URL (that otherwise would require writing some regular expressions to to do it yourself), as well as useful for purposes like checking if a value in a variable is an integer, or has a decimal value.

When using this function for filtering, it returns the filtered data, or false if the filter fails, making it convenient to be used within an if test.

In the most basic form it takes 2 arguments, a variable that holds a value you want to validate and the ID of the filter to apply:

// Email validation:
if (filter_var($email_address, FILTER_VALIDATE_EMAIL)) {
	...
}

// URL validation:
if (filter_var($url, FILTER_VALIDATE_URL)) {
	...
}

// Validating a product ID (must be an integer):
if (filter_var($product_id, FILTER_VALIDATE_INT)) {
	...
}

// Validating price (a decimal value, like 10 or 20.50):
if (filter_var($price, FILTER_VALIDATE_FLOAT)) {
	...
}
The FILTER_VALIDATE_INT often used with a third optional argument, to specify a minimum and/or a maximum allowed integer number, as an array of arguments:
if (filter_var($product_id, FILTER_VALIDATE_INT, array('min_range' => 1))) {
	...
}

// Or like so:
if (filter_var($category_name_length, FILTER_VALIDATE_INT, array('min_range' => 1, 'max_range' => 250))) {
	...
}

Now I'll show you an example how the filter_var() function can be used in a production script

Let's validate the email address field of an HTML form submitted on the 'Contact Us' page:
$errors = []; // An empty array for recording errors.

...

if (isset($_POST['email_address']) && filter_var($_POST['email_address'], FILTER_VALIDATE_EMAIL)) {

	$email = $_POST['email_address'];

} else {

	$errors['email_address'] = 'Please enter a valid email address!';

}
...

if (empty($errors)) {

	// Do something with the $email variable...

} else {

	// Use the $errors array which indexes correspond to input field names,
	// and their associated values are textual error messages to report a problem(s).
	...

}

As you can see the additional check isset($_POST['email_address']) precedes the filter_var() function, it's there because in real life situations, your form will be submitted not only by humans, but aso by all sorts of automated programs (bots and spiders, so to speak), some of them will disregard your html input field(s) submitting the form with absent (not set) values.

Feeding a "not set" value into filter_var() will produce a PHP error, that is why the given snippet of code makes sure that the value is actually "set" and only then validates it.

If you don't include this extra check and submit the form yourself in your browser in a normal way, you probably will never observe such error message anyway, as not filling an input field will send an empty string to the server that the filter_var() can work with.

The ways you could see those errors that occur in the real life on odd form submissions by automated software is to look at error logs, or through email messages, if a website has a custom error handler that sends email notifications when errors occur.

Another "production ready" example of using the filter_var() function, checking if product_id is more than or equals 1:
if(isset($_POST['product_id'])
	&& filter_var($_POST['product_id'], FILTER_VALIDATE_INT, array('min_range' => 1))) {
	...
}

Caution when you need to check if a value is more than or equals 0, let's say product quantities in a shopping cart, the content of the if conditional needs to be written with the explicit check for not being false:
if (filter_var($quantity, FILTER_VALIDATE_INT, array('min_range' => 0)) !== false) {
	...
}
	
Because 0 is a valid value in this case, the filter_var() function will return it, and the simple if check like this one: if (filter_var(...)) will interpret it as false. That is why you'd need to explicitly tell the if that you check only against a not false boolean value.

Another use of the filter_var() function is to sanitize data.

Larry Ulman, the author of a few books about PHP defines sanitation as:
Sanitization is a process of altering data by removing inappropriate characters in order to make the data meet expectation.

To perform sanitation with filter_var() you'd need to use one of its sanitizing filters, as the second argument. Here is a few of them:

FILTER_SANITIZE_ENCODED
URL encode string, optionally strip or encode special characters.
FILTER_SANITIZE_EMAIL
Remove all characters except letters, digits and !#$%&'*+-=?^_`{|}~@.[].
FILTER_SANITIZE_SPECIAL_CHARS
HTML-escape '"<>& and characters with ASCII value less than 32, optionally strip or encode other special characters
FILTER_SANITIZE_STRING
Strip tags, optionally strip or encode special characters.

A full list of sanitation filters can be found on the official PHP website: php.net/manual/en/filter.filters.sanitize.php

For example, to output title, removing any html tags that might be in the data returned from the database, you could use the following line:
echo '<h1>' . filter_var($row['title'], FILTER_SANITIZE_STRING) . '</h1>';

The FILTER_SANITIZE_STRING helps to prevent cross-site scripting attacks (XSS) as it will remove the <script> tags along the way.

Validating User Input With the filter_var() Function
This page was last updated on February 25, 2021
No comments have been posted so far
Leave a Comment