PHP filter

PHP filters are used to validate and filter data from non-secure sources, such as user input.


What are PHP filters?

PHP filters are used to validate and filter data from non-secure sources.

Testing, validating, and filtering user input or custom data are important parts of any web application.

PHP's filter extension is designed to make data filtering easier and faster.


Why use filters?

Almost all web applications rely on external input. This data usually comes from users or other applications (such as web services). By using filters, you can ensure that your application gets the correct input type.

You should always filter external data!

Input filtering is one of the most important application security topics.

What is external data?

· Input data from the form

· 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 by a specified filter

· filter_var_array() - Filter multiple variables through the same or different filters

· filter_input - Get an input variable and filter it Filtering

· filter_input_array - Get multiple input variables and filter them through the same or different filters


Example

##In the following example, We used the filter_var() function to verify an integer:

FILTER_VALIDATE_INT The filter uses an integer as the verification value.

<?php
header("Content-type:text/html;charset=utf-8");
$int = 123;

if(!filter_var($int, FILTER_VALIDATE_INT))
{
    echo("不是一个合法的整数");
}
else
{
    echo("是个合法的整数");
}
?>

Program running result:

is a legal integer


To view the complete function and filtering For a list of filters, visit our PHP Filter Reference Manual.


Validating and Sanitizing

There are two types of filters:

Validating Filtering Container:

· Used to validate user input

· Strict format rules (such as URL or E-Mail validation)

· If successful, return the expected type, if If it fails, it returns FALSE

Sanitizing Filter:

· Used to allow or prohibit the specified characters in the string

· No data format rules

· Always return string


##options and flags

options and flags are used to add additional filtering options to the specified filter.

Different filters have different options and flags.


Example

#In the following example, we verified using filter_var() with the "min_range" and "max_range" options An integer:

<?php
header("Content-type:text/html;charset=utf-8");
$var=300;
$int_options = array(
    "options"=>array
    (
        "min_range"=>0,   //最小值
        "max_range"=>256  //最大值
    )
);
if(!filter_var($var, FILTER_VALIDATE_INT, $int_options))
{
    echo("不是一个合法的整数");
}
else
{
    echo("是个合法的整数");
}
?>

Like the code above, options must be put into a related array called "options". If using flags, they don't need to be in an array.

Since the integer is "300", which is not within the specified range, the output of the above code will be:

is not a legal integer

For a complete list of functions and filters, please visit our PHP Filter Reference Manual. You can see the available options and flags for each filter.


Validating input

Let us try to validate the input from the form.

The first thing we need to do is confirm that the input data we are looking for exists.

Then we use the

filter_input() function to filter the input data.


Example

##In the following example, The input variable "email" is passed to the PHP page using GET:

<?php
header("Content-type:text/html;charset=utf-8");
if(!filter_has_var(INPUT_GET, "email"))
{
    echo("没有 email 参数");
}
else
{
    if (!filter_input(INPUT_GET, "email", FILTER_VALIDATE_EMAIL))
    {
        echo "不是一个合法的 E-Mail";
    }
    else
    {
        echo "是一个合法的 E-Mail";
    }
}
?>

Program execution result:

6.png

##Example explanation

The above example has an input variable (email) transmitted through the "GET" method:

1. Detect whether there is an "email" input variable of type "GET"

2. If there is an input variable, check whether it is a valid e-mail address


##Sanitize input

Let’s try to clean up the URL passed in from the form. First, we need to confirm that the input data we are looking for exists.

Then, we use the filter_input() function to purify the input data.


Example

In the following example, the input variable "url" is passed to the PHP page:

<?php
header("Content-type:text/html;charset=utf-8");
if(!filter_has_var(INPUT_GET, "url"))
{
    echo("没有 url 参数");
}
else
{
    $url = filter_input(INPUT_GET,
        "url", FILTER_SANITIZE_URL);
    echo $url;
}
?>

##Example explanation

FILTER_SANITIZE_URL Filter removes all illegal URL characters from the string.

The above example has an input variable (url) transmitted through the "GET" method:

1. Detect whether there is an "url" input variable of type "GET"

2. If this input variable exists, sanitize it (remove illegal characters) and store it in the $url variable

If the input variable is a string similar to this: " http:// www.ruåånoøøob.com/", the purified $url variable is as follows:

7.png


##Filter multiple inputs Forms usually consist of multiple input fields. To avoid repeated calls to filter_var or filter_input functions, we can use filter_var_array or the filter_input_array function.

ExampleWe use the filter_input_array() function to filter three GET variables. The received GET variables are a name, an age and an e-mail address:

<?php
header("Content-type:text/html;charset=utf-8");
$filters = array
(
    "name" => array
    (
        "filter_has_var"=>FILTER_SANITIZE_STRING
    ),
    "age" => array
    (
        "filter_has_var"=>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("年龄必须在 1 到 120 之间。<br>");
}
elseif(!$result["email"])
{
    echo("E-Mail 不合法<br>");
}
else
{
    echo("输入正确");
}
?>

Program execution result:

8.pngExplanation of examples

The above example has three input variables (name, age and email) transmitted through the "GET" method:

1. Set an array containing The name of the input variable and the filter used for the specified input variable

2. Call the filter_input_array() function, the parameters include the GET input variable and the array just set

3. Detect $result Are there any illegal inputs in the "age" and "email" variables in the variables? (If there is an illegal input, the input variable is FALSE after using the filter_input_array() function.)

The second argument to the filter_input_array() function can be an array or the ID of a single filter.

If this parameter is the ID of a single filter, then the specified filter will filter all values ​​in the input array.

If the parameter is an array, then the array must follow the following rules:

· It must be an associative array, and the input variables contained in it are the keys of the array (For example, "age" input variable)

· The value of this array must be the ID of the filter, or an array specifying filters, flags, and options


Use Filter Callback

FILTER_CALLBACK The filter uses user-defined functions to filter values

By using the FILTER_CALLBACK filter, you can call a custom function and use it as a filter. This way, we have full control over data filtering.

You can create your own custom function or use an existing PHP function.

Specify the function of the filter you are going to use according to the specified method of the specified option. In an associative array, with the name "options".

Example

In the example below, we use a custom The function converts all "_" to "."

<?php
header("Content-type:text/html;charset=utf-8");
function convertSpace($string)
{
    return str_replace("_", ".", $string);
}
$string = "www_php_cn!";
echo filter_var($string, FILTER_CALLBACK,
    array("options"=>"convertSpace"));
?>

Program running result:

www.php.cn!

Explanation of examples

The above example converts all "_" into ".":

1. Create a function that replaces "_" with "."

2. Call the filter_var() function, whose parameters are the FILTER_CALLBACK filter and the array containing our function


Continuing Learning
||
<?php header("Content-type:text/html;charset=utf-8"); $int = 123; if(!filter_var($int, FILTER_VALIDATE_INT)) { echo("不是一个合法的整数"); } else { echo("是个合法的整数"); } ?>
submitReset Code