SoFunction
Updated on 2025-03-10

Detailed explanation of using php filter

PHP filter

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

What is a PHP filter

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

Testing, validating, and filtering user input or custom data is an important part 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 is usually from users or other applications (such as web services). By using filters, you can make sure that the 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() - Filter a single variable through a specified filter

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

filter_input - Get an input variable and filter it

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

In the following example, we use the filter_var() function to verify an integer:

<?php
$int = 123;
if(!filter_var($int, FILTER_VALIDATE_INT))
{
    echo("Not a legal integer");
}
else
{
    echo("It's a legal integer");
}
?>

The above code uses the "FILTER_VALIDATE_INT" filter to filter variables. Since this integer is legal, the above code will output:

It's a legal integer

If we try to use a non-integer variable (such as "123abc"), the output will be: "Integer is not valid".

**

Validating and Sanitizing

**

There are two filters:

Validating filter:

Used to verify user input

Strict formatting rules (such as URL or E-Mail verification)

Returns the expected type if successful, and returns FALSE if failed

Sanitizing filter:

Used to allow or disable characters specified in a string

No data format rules

Always return string

Options and logos

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

Different filters have different options and logos.

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

<?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 legal integer");
}
else
{
    echo("It's a legal integer");
}
?>

Just like the above code, options must be placed in a related array called "options". If you use flags, you do not need to be inside the array.

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

Not a legal integer

Verify input

Let's try to verify the input from the form.

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

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

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

<?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 legal E-Mail";
    }
    else
    {
        echo "It's a legal E-Mail";
    }
}
?>

The above example test results are as follows:

It's a legal E-Mail

Example explanation

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

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

If an input variable exists, check if it is a valid e-mail address

Purify input

Let's try to clean up the URLs that are coming from the form.

First, we want to confirm whether the input data we are looking for exists.

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

In the following example, the input variable "url" 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) transmitted through the "GET" method:

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

If this input variable exists, purify it (delete illegal characters) and store it in the $url variable

Filter multiple inputs

A form is usually composed 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 functions.

In this example, we use the filter_input_array() function to filter three GET variables. The received GET variable is a name, an age, and an e-mail address:

<?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.");
}
elseif(!$result["email"])
{
    echo("E-Mail is illegal<br>");
}
else
{
    echo("Input correct");
}
?&gt;

Example explanation

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

Sets an array containing the name of the input variable and the filter used for the specified input variable

Call filter_input_array() function, the parameters include GET input variables and the array just set

Detects whether the "age" and "email" variables in the $result variable have illegal input. (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 the ID of an array or a single filter.

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

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

Must be an associative array, where the input variables contained are keys to the array (such as the "age" input variable)

The value of this array must be the filter ID, or an array that specifies filters, flags, and options.

Using Filter Callback

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

You can create your own custom functions or use existing PHP functions.

Specify the filter functions you are preparing to use according to the specified method of the specified options. In the associative array, with the name "options".

In the following example, we use a custom function to convert all "_" into ".":

<?php
function convertSpace($string)
{
    return str_replace("_", ".", $string);
}
$string = "www_*****_com!";
echo filter_var($string, FILTER_CALLBACK,
array("options"=>"convertSpace"));
?>

The result of the above code is as follows:

www.*****.com!

Example explanation

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

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

Call the filter_var() function, its parameters are the FILTER_CALLBACK filter and an array containing our functions

This is the end of this article about the detailed explanation of the use of php filters. For more related php filter content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!