search
HomeBackend DevelopmentPHP TutorialImplementation method of PHP filter Page 1/2_PHP tutorial
Implementation method of PHP filter Page 1/2_PHP tutorialJul 21, 2016 pm 03:36 PM
phpandSafetyaccomplishdatamethodsourceuseoffilterfilterNoverify

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.

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

Filter extensions for PHP are designed to make data filtering easier and faster.
Why use filters?
Nearly 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 forms
Cookies
Server variables
Database query results
Functions and filters
To filter variables, use one of the filter functions below:

filter_var() - Filter a single variable by a specified filter
filter_var_array() - Filter multiple variables by the same or different filters
filter_input - Get an input variable and Filter it
filter_input_array - take multiple input variables and filter them through the same or different filters
In the example below, we validate an integer using the filter_var() function:

Copy code The code is as follows:

$int = 123;

if( !filter_var($int, FILTER_VALIDATE_INT))
{
echo("Integer is not valid");
}
else
{
echo("Integer is valid");
}
?>

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

If we try to use a non-integer variable, the output is: "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 filter:
Used to validate user input
Strict format rules (such as URL or E-Mail validation)
Returns the expected type if successful, otherwise returns FALSE
Sanitizing filter:
Used to allow or disallow 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 the specified filter.

Different filters have different options and flags.

In the example below, we validate an integer using filter_var() with the "min_range" and "max_range" options:
Copy code The code is as follows:

$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, 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 atmosphere, 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.
Validate input
Let’s try validating input from a 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.

In the following example, the input variable "email" is passed to the PHP page:
Copy the code The code is as follows:

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";
}
}
?>

Explanation of the example:
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 There is an input variable, check if it is a valid email address
Sanitize input
Let’s try to clean up the URL passed in from the form.

First, we want to confirm that 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:
Copy the code The code is as follows:

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:
Above The example has an input variable (url) transmitted through the "POST" method:

Detects whether there is a "url" input variable of type "POST"
If this input variable exists, sanitize it ( Delete illegal characters) and store it in the $url variable
If the input variable is similar to this: "http://www.W3#$%S^%$#ool.com.cn/", then after purification The $url variable should look like this:

http://www.W3School.com.cn/ Filter multiple inputs
Forms usually consist of multiple input fields. To avoid repeated calls to filter_var or filter_input, we can use filter_var_array or the 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:
Copy code The code is as follows:

$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 a number between 1 and 120.
");
}
elseif(! $result["email"])
{
echo("E-Mail is not valid.
");
}
else
{
echo ("User input is valid");
}
?>

Explanation of the example:
The above example has three input variables (name , age and email)

Set an array that contains the name of the input variable, and the filter for the specified input variable
Call the filter_input_array function, the parameters include the GET input variable and the array just set
Check whether there are illegal inputs in the "age" and "email" variables in the $result variable. (If there is an illegal input,)
The second parameter of the filter_input_array() function can be an array or the ID of a single filter.

If the 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:

must be an associative array containing the input variables that are the keys of the array (such as the "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
By using the FILTER_CALLBACK filter, you can call a custom function to It works as a filter. This way, we have full control over data filtering.

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

Specify the function you want to use for the filter, the same way you specify options.

In the example below, we use a custom function to convert all "_" to spaces:
Copy code Code As follows:

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 like this:

Peter is a great guy! Example explanation:
The above example converts all "_" into spaces:

Create a The function
that replaces "_" with spaces calls the filter_var() function, whose parameters are the FILTER_CALLBACK filter and the array containing our function

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/322077.htmlTechArticlePHP 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...
Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
php怎么把负数转为正整数php怎么把负数转为正整数Apr 19, 2022 pm 08:59 PM

php把负数转为正整数的方法:1、使用abs()函数将负数转为正数,使用intval()函数对正数取整,转为正整数,语法“intval(abs($number))”;2、利用“~”位运算符将负数取反加一,语法“~$number + 1”。

php怎么实现几秒后执行一个函数php怎么实现几秒后执行一个函数Apr 24, 2022 pm 01:12 PM

实现方法:1、使用“sleep(延迟秒数)”语句,可延迟执行函数若干秒;2、使用“time_nanosleep(延迟秒数,延迟纳秒数)”语句,可延迟执行函数若干秒和纳秒;3、使用“time_sleep_until(time()+7)”语句。

php字符串有没有下标php字符串有没有下标Apr 24, 2022 am 11:49 AM

php字符串有下标。在PHP中,下标不仅可以应用于数组和对象,还可应用于字符串,利用字符串的下标和中括号“[]”可以访问指定索引位置的字符,并对该字符进行读写,语法“字符串名[下标值]”;字符串的下标值(索引值)只能是整数类型,起始值为0。

php怎么除以100保留两位小数php怎么除以100保留两位小数Apr 22, 2022 pm 06:23 PM

php除以100保留两位小数的方法:1、利用“/”运算符进行除法运算,语法“数值 / 100”;2、使用“number_format(除法结果, 2)”或“sprintf("%.2f",除法结果)”语句进行四舍五入的处理值,并保留两位小数。

php怎么读取字符串后几个字符php怎么读取字符串后几个字符Apr 22, 2022 pm 08:31 PM

在php中,可以使用substr()函数来读取字符串后几个字符,只需要将该函数的第二个参数设置为负值,第三个参数省略即可;语法为“substr(字符串,-n)”,表示读取从字符串结尾处向前数第n个字符开始,直到字符串结尾的全部字符。

php怎么根据年月日判断是一年的第几天php怎么根据年月日判断是一年的第几天Apr 22, 2022 pm 05:02 PM

判断方法:1、使用“strtotime("年-月-日")”语句将给定的年月日转换为时间戳格式;2、用“date("z",时间戳)+1”语句计算指定时间戳是一年的第几天。date()返回的天数是从0开始计算的,因此真实天数需要在此基础上加1。

php怎么替换nbsp空格符php怎么替换nbsp空格符Apr 24, 2022 pm 02:55 PM

方法:1、用“str_replace(" ","其他字符",$str)”语句,可将nbsp符替换为其他字符;2、用“preg_replace("/(\s|\&nbsp\;||\xc2\xa0)/","其他字符",$str)”语句。

php怎么查找字符串是第几位php怎么查找字符串是第几位Apr 22, 2022 pm 06:48 PM

查找方法:1、用strpos(),语法“strpos("字符串值","查找子串")+1”;2、用stripos(),语法“strpos("字符串值","查找子串")+1”。因为字符串是从0开始计数的,因此两个函数获取的位置需要进行加1处理。

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools