PHP Filter
Posted by tutor | Posted in PHP Tutorial | Posted on 17-12-2009-05-2008
0
Filters are used to validate and filter data coming from insecure sources, like user input.
Its an important part of web application, to filter the user input.
The PHP filter extension makes data filtering easier and quicker.
Today, almost all web applications are based on user interativity, which means depending on external input. While the external input can be a user entering data or it may come from some other web service. Filters are used to make sure that your application gets the correct input type.
All the external data should be filtered for security purposes. The external data we are talking about can be any of these:
- Input data from a form
- Cookies
- Web services data
- Server variables
- Database query results
Functions and Filters
There are various filter varianbles available. You can use one of the following filter functions:
- filter_var() – Filters a single variable with a specified filter
- filter_var_array() – Filter several variables with the same or different filters
- filter_input – Get one input variable and filter it
- filter_input_array – Get several input variables and filter them with the same or different filters
In the example below, we validate an integer using the filter_var() function:
$int = 123;
if(!filter_var($int, FILTER_VALIDATE_INT))
{
echo(“Integer is not valid”);
}
else
{
echo(“Integer is valid”);
}
?>
The code above uses “FILTER_VALIDATE_INT” to filter the variable. Since the integer is valid, the output of the code above will be: “Integer is valid”.
If we try with a variable that is not an integer (like “123abc”), the output will be: “Integer is not valid”.
Validating and Sanitizing
In PHP we have two kinds of filters:
- Validating filters:They are used to validate user input, They have strict format rules like URL or E-mail validating. It returns the expected type on success or FALSE on failure.
- Sanitizing filters:They are used to allow or disallow specified characters in a string. There are no data format rules, and they Always return the string whether success or failure.
Options and Flags
Options and flags are used to add additional filtering options to the specified filters. Each filter has different options and flags.
In the example below, we validate an integer using the filter_var() and the “min_range” and “max_range” options:
$var=300;
$int_options = array(
“options”=>array
(
“min_range”=>0,
“max_range”=>256
)
);
if(!filter_var($var, FILTER_VALIDATE_INT, $int_options))
{
echo(“Integer is not valid”);
}
else
{
echo(“Integer is valid”);
}
?>
Integer is not valid
Options must always be put in an associative array with the name “options”. But if a flag is used it does not need to be in an array.
