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.
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)) {
...
}
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
$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.
if(isset($_POST['product_id'])
&& filter_var($_POST['product_id'], FILTER_VALIDATE_INT, array('min_range' => 1))) {
...
}
if (filter_var($quantity, FILTER_VALIDATE_INT, array('min_range' => 0)) !== false) {
...
}
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
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.
