Summary: in this tutorial, you will learn how to use the PHP filter_var()
function to sanitize and validate data.
Introduction to the PHP filter_var() function #
The filter_var()
function allows you to filter a variable using a validation or sanitization filters.
Here’s the syntax of the filter_var()
function:
filter_var ( mixed $value , int $filter = FILTER_DEFAULT , array|int $options = 0 ) : mixed
Code language: PHP (php)
The filter_var()
function has three parameters:
$value
is the value you want to validate or sanitize.$filter
is the filter id to apply. The filter id determines how the function will filter the$value
.$options
is an associative array of filter options or a list of flags separated by the pipe character (|
).
The filter()
function returns the filtered value, or false
if fails
Validating data #
The following example uses the filter_var function to validate data:
<?php
$id = '100';
$result = filter_var($id, FILTER_VALIDATE_INT);
echo $result === false ? "Invalid ID" : "Valid ID: $result";
Code language: HTML, XML (xml)
Output:
Valid ID: 100
How it works.
First, declare a variable $id
with the initial value '100'
:
$id = '100';
Code language: PHP (php)
In practice, the $id
may come from the query string or external API.
Second, check if$id
is an interger using the filter id FILTER_VALIDATE_INT:
$result = filter_var($id, FILTER_VALIDATE_INT);
Code language: PHP (php)
The FILTER_VALIDATE_INT
validates if $id
is an integer. In this example, the value of the $id
is a string '100'
, the function converts it to an integer 100
.
Third, change the value of the $id
to 'abc'
, the filter_var()
function will return false
:
<?php
$id = 'abc';
$result = filter_var($id, FILTER_VALIDATE_INT);
echo $result === false ? "Invalid ID" : "Valid ID: $result";
Code language: HTML, XML (xml)
Output:
Invalid ID
The following example uses the filter_var
function to check if id is an integer and in the range of 1 and 100:
<?php
$id = 120;
$result = filter_var($id, FILTER_VALIDATE_INT, [
'options' => [
'min_range' => 1,
'max_range' => 100,
]
]);
echo $result === false ? "Invalid ID" : "Valid ID: $result";
Code language: HTML, XML (xml)
Output:
Invalid ID
Sanitizing data #
The following example uses the filter_var()
function to sanitize a number:
<?php
$id = '120abc';
$result = filter_var($id, FILTER_SANITIZE_NUMBER_INT);
echo $result === false ? "Invalid ID" : "Valid ID: $result";
Code language: PHP (php)
Output:
Valid ID: 120
The filter_var()
function with the FILTER_SANITIZE_NUMBER_INT
filters will remove all characters except the digits, plus, and minus signs from the id
variable.
Summary #
- Use the
filter_var()
function to validate or sanitize a variable.