PHP Filters
PHP filters are used for validating and sanitizing data from insecure sources, such as user input.
What are PHP Filters?
PHP filters are used for validating and sanitizing data from insecure sources.
Testing, validating, and sanitizing user input or custom data are essential parts of any web application.
The design of PHP's filter extension aims to make data filtering easier and faster.
Why Use Filters?
Almost all web applications rely on external input. This data typically comes from users or other applications (such as web services). By using filters, you can ensure that the application receives the correct type of input.
You should always filter external data!
Input filtering is one of the most critical aspects of application security.
What is external data?
- Input data from forms
- Cookies
- Web services data
- Server variables
- Database query results
Functions and Filters
To filter variables, use one of the following filter functions:
filter_var()
- Filters a single variable with a specified filterfilter_var_array()
- Filters multiple variables with the same or different filtersfilter_input()
- Gets an input variable and filters itfilter_input_array()
- Gets multiple input variables and filters them with the same or different filters
In the following example, we use the filter_var()
function to validate an integer:
Example
<?php
$int = 123;
if (!filter_var($int, FILTER_VALIDATE_INT)) {
echo "Not a valid integer";
} else {
echo "Valid integer";
}
?>
The above code uses the "FILTER_VALIDATE_INT" filter to validate the variable. Since the integer is valid, the code will output:
Valid integer
If we try to use a non-integer variable (like "123abc"), it will output: "Integer is not valid".
For a complete list of functions and filters, visit our PHP Filter Reference Manual.
Validating and Sanitizing
There are two types of filters:
Validating Filters:
- Used to validate user input
- Strict format rules (e.g., URL or E-Mail validation)
- Returns the expected type if successful, otherwise returns FALSE
Sanitizing Filters:
- Allows or disallows specified characters in a string
- No data format rules
- Always returns a string
Options and Flags
Options and flags are used to add additional filtering options to specified filters.
Different filters have different options and flags.
In the following example, we use filter_var()
with "min_range" and "max_range" options to validate an integer:
Example
<?php
$var = 300;
$int_options = array(
"options" => array(
"min_range" => 0,
"max_range" => 256
)
);
if (!filter_var($var, FILTER_VALIDATE_INT, $int_options)) {
echo "Not a valid integer";
} else {
echo "Valid integer";
}
?>
As in the above code, options must be placed in an associative array named "options". If using flags, they do not need to be in an array.
Since the integer is "300", which is outside the specified range, the output of the above code will be:
Not a valid integer
For a complete list of functions and filters, visit our PHP Filter Reference Manual. You can see the available options and flags for each filter.
Validating Input
Let's try to validate input from a form.
The first thing we need to do is to confirm whether the input data we are looking for exists.
Then we use the filter_input()
function to filter the input data.
In the following example, the input variable "email" is sent to the PHP page:
Example
<?php
if (!filter_has_var(INPUT_GET, "email")) {
echo "No email parameter";
} else {
if (!filter_input(INPUT_GET, "email", FILTER_VALIDATE_EMAIL)) {
echo "Not a valid E-Mail";
} else {
echo "Valid E-Mail";
}
}
?>
The above example will test as follows:
Example Explanation
The above example has an input variable (email) sent via "GET" method:
Valid E-Mail
- Check if the "GET" type "email" input variable exists.
- If the input variable exists, check if it is a valid email address.
Sanitize Input
Let's try to clean up the URL received from the form.
First, we need to confirm if the input data we are looking for exists.
Then, we use the filter_input() function to sanitize the input data.
In the following example, the "url" input variable is passed to the PHP page:
<?php
if (!filter_has_var(INPUT_GET, "url")) {
echo("No url parameter");
} else {
$url = filter_input(INPUT_GET, "url", FILTER_SANITIZE_URL);
echo $url;
}
?>
Example Explanation
The above example has an input variable (url) sent via the "GET" method:
Check if the "GET" type "url" input variable exists.
If this input variable exists, sanitize it (remove illegal characters) and store it in the $url variable.
If the input variable is a string like "http://www.ruåånoøøob.com/", the sanitized $url variable will look like this:
Filter Multiple Inputs
Forms usually consist of multiple input fields. To avoid repetitive calls to filter_var or filter_input functions, we can use the filter_var_array or filter_input_array function.
In this example, we use the filter_input_array() function to filter three GET variables. The received GET variables are a name, an age, and an email address:
Example
<?php
$filters = array(
"name" => array(
"filter" => FILTER_SANITIZE_STRING
),
"age" => array(
"filter" => FILTER_VALIDATE_INT,
"options" => array(
"min_range" => 1,
"max_range" => 120
)
),
"email" => FILTER_VALIDATE_EMAIL
);
$result = filter_input_array(INPUT_GET, $filters);
if (!$result["age"]) {
echo("Age must be between 1 and 120.<br>");
} elseif (!$result["email"]) {
echo("Invalid E-Mail<br>");
} else {
echo("Input is correct");
}
?>
Example Explanation
The above example has three input variables (name, age, and email) sent via the "GET" method:
Set an array containing the names of the input variables and the filters to be applied to each input variable.
Call the filter_input_array() function with the GET input variables and the array set earlier.
Check if the "age" and "email" variables in the $result variable have illegal input. (If there is illegal input, the input variable will be FALSE after using the filter_input_array() function.)
The second parameter of the filter_input_array() function can be an array or a single filter ID.
If this parameter is a single filter ID, then this specified filter will filter all values in the input array.
If this parameter is an array, then this array must follow these rules:
It must be an associative array where the input variables are the keys (like the "age" input variable).
The values of this array must be the filter ID, or an array that specifies the filter, flags, and options.
Using Filter Callback
By using the FILTER_CALLBACK filter, you can call a custom function and use it as a filter. This gives us full control over the data filtering.
You can create your own custom function or use an existing PHP function.
Specify the function you intend to use for filtering according to the specified options. In the associative array, with the name "options".
In the following example, we use a custom function to replace all "_" with ".":
Example
<?php
function convertSpace($string) {
return str_replace("_", ".", $string);
}
$string = "www_tutorialpro.org!";
echo filter_var($string, FILTER_CALLBACK, array("options" => "convertSpace"));
?>
echo filter_var($string, FILTER_CALLBACK,
array("options"=>"convertSpace"));
?>
The result of the above code is as follows:
Example Explanation
The above example converts all "_" to ".":
Create a function that replaces "_" with "."
Call the filter_var() function with the FILTER_CALLBACK filter and an array containing our function ```