Home > Backend Development > PHP Tutorial > Related knowledge about PHP filter (Filter)

Related knowledge about PHP filter (Filter)

jacklove
Release: 2023-03-25 15:04:01
Original
1506 people have browsed it

PHP Filter is used to verify and filter data from non-secure sources, such as user input. This article will learn more about filters in detail.

What is a PHP filter?

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.

The PHP filter extension is 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 following filter functions:

filter_var() - Filter a single variable by a specified filter

filter_var_array() - Filter by the same or different filters to filter multiple variables

filter_input - Get an input variable , and filter it

filter_input_array - Get multiple input variables, and filter them by Filter them with the same or different filters

In the following example, we validate an integer using the filter_var() function:

<?php
$int = 123;
if(!filter_var($int, FILTER_VALIDATE_INT))
 {
 echo("Integer is not valid");
 }
else
 {
 echo("Integer is valid");
 }
?>
Copy after login

The above code uses the "FILTER_VALIDATE_INT" filter 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, please 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, or FALSE if failed

Sanitizing filter:

Used to allow or Disallows the specified characters in the string

No data format rules

Always returns the string

Options and flags

Options and flags are used to specify Filters add additional filtering options.

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:

<?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");
 }
?>
Copy after login

Like the code above, the options must be put in a in 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 "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 to validate the input from the form.

The first thing we need to do is confirm whether 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:

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

Explanation of the example:

The above example has one passed through the "GET" method Input variable (email):

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

If there is an input variable, check whether it is a valid email address

Purify input

Let's try to clean up the URL passed 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.

In the following example, the input variable "url" is passed 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);
 }
?>
Copy after login

Explanation of the example:

The above example has a transmission via the "POST" method Input variable (url):

Detect whether there is a "url" input variable of "POST" type

If this input variable exists, purify it (remove illegal characters), and It is stored in the $url variable

If the input variable is similar to this: "http://www.W3 illegal ol.com.c character n/", then the purified $url variable should be like this of:

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 GET variables received are a name, an age, and an email 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 a number between 1 and 120.<br />");
 }
elseif(!$result["email"])
 {
 echo("E-Mail is not valid.<br />");
 }
else
 {
 echo("User input is valid");
 }
?>
Copy after login

例子解释:

上面的例子有三个通过 "GET" 方法传送的输入变量 (name, age and email)

设置一个数组,其中包含了输入变量的名称,以及用于指定的输入变量的过滤器

调用 filter_input_array 函数,参数包括 GET 输入变量及刚才设置的数组

检测 $result 变量中的 "age" 和 "email" 变量是否有非法的输入。(如果存在非法输入,)

filter_input_array() 函数的第二个参数可以是数组或单一过滤器的 ID。

如果该参数是单一过滤器的 ID,那么这个指定的过滤器会过滤输入数组中所有的值。

如果该参数是一个数组,那么此数组必须遵循下面的规则:

必须是一个关联数组,其中包含的输入变量是数组的键(比如 "age" 输入变量)

此数组的值必须是过滤器的 ID ,或者是规定了过滤器、标志以及选项的数组

使用 Filter Callback

通过使用 FILTER_CALLBACK 过滤器,可以调用自定义的函数,把它作为一个过滤器来使用。这样,我们就拥有了数据过滤的完全控制权。

您可以创建自己的自定义函数,也可以使用已有的 PHP 函数。

规定您准备用到过滤器函数的方法,与规定选项的方法相同。

在下面的例子中,我们使用了一个自定义的函数把所有 "_" 转换为空格:

<?phpfunction convertSpace($string)
{
return str_replace("_", " ", $string);
}$string = "Peter_is_a_great_guy!";
echo filter_var($string, FILTER_CALLBACK, array("options"=>"convertSpace"));
?>
Copy after login

以上代码的结果是这样的:

Peter is a great guy!

例子解释:

上面的例子把所有 "_" 转换成空格:

创建一个把 "_" 替换为空格的函数

调用 filter_var() 函数,它的参数是 FILTER_CALLBACK 过滤器以及包含我们的函数的数组。

本篇对过滤器进行了讲解,更多的学习资料清关注php中文网即可观看。

相关推荐:

关于对PHP 异常处理的操作

关于PHP 文件打开/读取/读取相关知识

关于PHP Include 文件的讲解

The above is the detailed content of Related knowledge about PHP filter (Filter). For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template