A comprehensive analysis of _php examples of PHP filter filters

Source: Internet
Author: User
Tags types of filters

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

What is a PHP filter?

PHP filters are used to validate and filter data from unsecured sources.

Validating and filtering user input or custom data is an important part of any WEB application.

The purpose of designing a PHP filter extension is 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 a filter, you can ensure that your program gets the correct input type.

You should always filter the external data!

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

What is external data?

• Input data from the form

Cookies

• 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 filter

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

filter_input-Get an input variable and filter it

Filter_input_array-gets multiple input variables and filters them through the same or different filters

In the following example, we use the Filter_var () function to validate an integer:

<?php
$int = 123;
if (!filter_var ($int, filter_validate_int))
{
echo ("Integer is not valid");
}
else
{
echo ("Integer is valid");
}

The code above uses the "Filter_validate_int" filter to filter variables. Because this integer is legitimate, the output of the code is: "The integer is valid".

If we try to use a variable with a non integer, the output is: "The Integer is not valid".

For a complete list of functions and filters, please visit our PHP Filter reference manual.

Validating and sanitizing

There are two types of filters:

Validating filter:

• For validating user input

• Strict formatting rules (e.g. URL or e-mail validation)

• Returns the expected type if successful and FALSE if it fails

Sanitizing Filter:

• Used to allow or disallow characters specified in a 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.

In the following example, we validated an integer with the Filter_var () and the "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 ("Integer is not valid");
}
else
{
echo ("Integer is valid");
}

Like the code above, the option must be placed in an associated array named "Options." If you use a flag, you do not need to be inside the array.

Because the integer is "300", it is outside the specified range, the output of the above code will be "integer is not valid".

For a complete list of functions and filters, please visit the PHP Filter reference manual provided by W3school. You can see the available options and flags for each filter.

Validating input

Let's try validating the input from the form.

The first thing we need to do is confirm that we have 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 uploaded to the PHP page:

<?php
if (!filter_has_var (input_get, "email"))
{
echo ("INPUT type does not exist");
}
else
{
if (!filter_input (input_get, "email", filter_validate_email))
{
echo "e-mail is not valid";
}
Else
{
echo ' e-mail is valid ';
}
}
? >

Example Explanation:

The above example has an input variable (email) that passes through the "Get" method:

1. Detect the existence of "get" type of "email" input variable

2. If there is an input variable, check if it is a valid mail address

Purifying input

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

First, we want to make sure we have the input data we're looking for.

We then use the Filter_input () function to purify the input data.

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

<?php
if (!filter_has_var (input_post, "url")
{
echo ("INPUT type does not exist");
}
else
{
$url = filter_input (input_post, URL, filter_sanitize_url);
}

Example Explanation:

The example above has an input variable (URL) that is routed through the "POST" method:

1. Detect the existence of a "POST" type of "url" input variable

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

If the input variable is like this: "Http://www.W3 ol.com.c character n/", then the purified $url variable should be:
http://www.W3School.com.cn/

Filter multiple Inputs

A form is usually made up of multiple input fields. To avoid repeated calls to Filter_var or filter_input, we can use the Filter_var_array or the Filter_input_array function.

In this case, we use the Filter_input_array () function to filter three get variables. The receive variable received 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);(Array (3) {[' Name ']=> string (1) ' 1 ' [' Age ']=> bool (false) [] Email "]=> String (8)" 1@qq.com "}"
if (! $result [' age '])
{
echo ("Age must is a number between 1 and 120.&L t;br/> ");
}
ElseIf (! $result ["email"])
{
echo ("E-valid.<br/>");
}
else
{
echo ("User input is valid");
}

Example Explanation:

The above example has three input variables passed through the "Get" method (name, age and email)

1. Set an array that contains the name of the input variable and the filter used for the specified input variable

2. Call the Filter_input_array function, the parameter includes the Get input variable and the array just set

3. Detect whether the "age" and "email" variables in the $result variable have illegal input. (if there is an illegal input,)

The second parameter of the Filter_input_array () function can be the ID of an array or a single filter.

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

If the argument is an array, the array must follow the following rules:

• Must be an associative array containing input variables that are the keys of the array (such as "age" input variables)

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

Using the 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 the data filtering.

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

The method that you want to use for the filter function is the same as the method that prescribes the option.

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

<?php
function Convertspace ($string)
{return
Str_replace ("_", "", $string);
}
$string = "peter_is_a_great_guy!";
Echo Filter_var ($string, Filter_callback, Array ("Options" => "Convertspace"));

The result of the above code is this:

Peter is a great guy!

Example Explanation:

The above example converts all "_" to Spaces:

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

2. Call the Filter_var () function, its arguments are filter_callback filters and an array containing our functions

The above is a small series to introduce the PHP filter filters comprehensive analysis, I hope to help everyone, if you have any questions please give me a message, small series will promptly reply to everyone. Here also thank you very much for the cloud Habitat Community website support!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.