Php 简明教程

PHP – Filters

重要的是,在 PHP 应用程序中处理之前,验证以客户端请求的形式接收的输入数据。为了执行输入验证,PHP 中的 filter 扩展程序提供了一些 filter 函数,并由预定义的 filter 常量和标志支持。PHP 库的 filter 扩展程序还有助于通过 GET 或 POST 方法净化接收的输入。

It is important that the input data received in the form of client request is validated before processing in a PHP application. To perform input validation, the filter extension in PHP provides a number of filter functions, backed up by predefined filter constants and flags. The filter extension of PHP library also helps in sanitizing the input received by either GET or POST methods.

filter 扩展程序是一项强大的功能,有助于防止安全漏洞,例如 SQL 注入和跨站脚本攻击。扩展程序有两种类型的过滤器 −

The filter extension is a powerful feature that helps prevention of security vulnerabilities, such as SQL injection and cross-site scripting. The extension has two types of filters −

Validation Filters

验证过滤器检查数据是否符合某些标准。例如,您想确保用户正确地输入了 HTML 表单中的电子邮件字段。FILTER_VALIDATE_EMAIL 将确定数据是否有效的电子邮件地址。但是,验证过滤器不会更改数据本身。

Validation filters check if the data meets certain criteria. For example, you want to ensure that the user has correctly input an email field in the HTML form. The FILTER_VALIDATE_EMAIL will determine if the data is a valid email address. The validation filters, however, will not change the data itself.

Sanitization Filters

清理是指从输入中删除不需要的字符的过程。因此,它可以通过删除不需要的字符来更改数据。例如,传入 FILTER_SANITIZE_EMAIL 将删除不适合包含在电子邮件地址中的字符,而不会执行验证。

Sanitization refers to the process of removing undesired characters from the input. Hence, it may alter the data by removing undesired characters. For example, passing in FILTER_SANITIZE_EMAIL will remove characters that are inappropriate for an email address to contain, without performing validation.

Filter Flags

PHP 中的 filter 扩展程序定义了许多 filter flags 如下所示 −

The filter extension in PHP defines a number of filter flags as follows −

Sr.No

ID & Description

1

FILTER_FLAG_STRIP_LOW Strips characters that have a numerical value <32.

2

FILTER_FLAG_STRIP_HIGH Strips characters that have a numerical value >127.

3

FILTER_FLAG_STRIP_BACKTICK Strips backtick characters.

4

FILTER_FLAG_ALLOW_FRACTION Allows a period (.) as a fractional separator in numbers.

5

FILTER_FLAG_ALLOW_THOUSAND Allows a comma (,) as a thousands separator in numbers.

6

FILTER_FLAG_ALLOW_SCIENTIFIC Allows an e or E for scientific notation in numbers.

7

FILTER_FLAG_NO_ENCODE_QUOTES If this flag is present, single (') and double (") quotes will not be encoded.

8

FILTER_FLAG_ENCODE_LOW Encodes all characters with a numerical value <32.

9

FILTER_FLAG_ENCODE_HIGH Encodes all characters with a numerical value >127.

10

FILTER_FLAG_ENCODE_AMP Encodes ampersands (&).

11

FILTER_NULL_ON_FAILURE Returns null for unrecognized values.

12

FILTER_FLAG_ALLOW_OCTAL Regards inputs starting with a zero (0) as octal numbers.

13

FILTER_FLAG_ALLOW_HEX Regards inputs starting with 0x or 0X as hexadecimal numbers.

14

FILTER_FLAG_EMAIL_UNICODE Allows the local part of the email address to contain Unicode characters.

15

FILTER_FLAG_IPV4 Allows the IP address to be in IPv4 format.

16

FILTER_FLAG_IPV6 Allows the IP address to be in IPv6 format.

17

FILTER_FLAG_NO_PRIV_RANGE Fails validation for the following private IPv4 ranges: 10.0.0.0/8, 172.16.0.0/12 and 192.168.0.0/16.

18

FILTER_FLAG_NO_RES_RANGE Fails validation for the following reserved IPv4 ranges: 0.0.0.0/8, 169.254.0.0/16, 127.0.0.0/8 and 240.0.0.0/4. Fails validation for the following reserved IPv6 ranges: ::1/128, ::/128, ::ffff:0:0/96 and fe80::/10.

19

FILTER_FLAG_GLOBAL_RANGE Fails validation for non global IPv4/IPv6 ranges

20

FILTER_FLAG_SCHEME_REQUIRED Requires the URL to contain a scheme part.

21

FILTER_FLAG_HOST_REQUIRED Requires the URL to contain a host part.

22

FILTER_FLAG_PATH_REQUIRED Requires the URL to contain a path part.

23

FILTER_FLAG_QUERY_REQUIRED Requires the URL to contain a query string.

24

FILTER_REQUIRE_SCALAR Requires the value to be scalar.

25

FILTER_REQUIRE_ARRAY Requires the value to be an array.

26

FILTER_FORCE_ARRAY If the value is a scalar, it is treated as array with the scalar value as only element.

Filter Functions

过滤器扩展包括以下内容: filter functions

The filter extension includes the following filter functions

Sr.No

ID & Description

1

filter_has_var() Checks if variable of specified type exists

2

filter_id() Returns the filter ID belonging to a named filter

3

filter_input_array() Gets external variables and optionally filters them

4

filter_input () Gets a specific external variable by name and filters it

5

filter_list() Returns a list of all supported filters

6

filter_var_array() Gets multiple variables and optionally filters them

7

filter_var() Filters a variable with a specified filter

Predefined Constants

以上函数使用一个名为 input_type 的参数,它是用来表示向 PHP 脚本提供输入用于筛选目的的预定义枚举常量之一。

The above functions use one parameter called input_type which is one of the predefined enumerated constants representing how the input has been provided to the PHP script for filtering purpose.

Constant

Types

INPUT_POST (int)

POST Variables

INPUT_GET (int)

GET Variables

INPUT_COOKIE (int)

COOKIE Variables

INPUT_ENV (int)

ENV Variables

INPUT_SERVER (int)

SERVER Variables

INPUT_SESSION (int)

SESSION Variables

INPUT_REQUEST (int)

REQUEST Variables

filter_has_var() function

filter_has_var() 函数检查指定类型变量是否存在。

The filter_has_var() function checks if variable of specified type exists.

filter_has_var(int $input_type, string $var_name): bool

input_type 是预定义常量之一,如 INPUT_GET、INPUT_POST、INPUT_COOKIE、INPUT_SERVER 或 INPUT_ENV;var_name 参数是用于检查的变量名称。该函数在成功时返回 true,失败时返回 false。

The input_type is one of predefined constants INPUT_GET, INPUT_POST, INPUT_COOKIE, INPUT_SERVER, or INPUT_ENV; where as the var_name parameter is the name of a variable to check. The function returns true on success or false on failure.

Example

访问 XAMPP 服务器上的以下 PHP 脚本。

Visit the following PHP script on the XAMPP server.

<?php
   if (!filter_has_var(INPUT_GET, "email")) {
      echo("Email not found");
   } else {
      echo("Email found");
   }
?>

它将生成以下 output

It will produce the following output

Email found

filter_input() function

filter_input() 函数通过名称获取特定外部变量并根据应用的过滤器常量过滤它

The filter_input() function gets a specific external variable by name and filters it accorfing to the applied filter constant

filter_input(
   int $type,
   string $var_name,
   int $filter = FILTER_DEFAULT,
   array|int $options = 0
): mixed

type 参数是常量之一,如 INPUT_GET、INPUT_POST、INPUT_COOKIE、INPUT_SERVER 或 INPUT_ENV。第二个参数是 var_name,这是用于获取的变量名称。你可以使用要应用的过滤器。使用任何预定义筛选标志。如果省略,则使用 FILTER_DEFAULT

The type parameter is one of the constants INPUT_GET, INPUT_POST, INPUT_COOKIE, INPUT_SERVER, or INPUT_ENV. Second parameter is var_name, the name of a variable to get. You can use the filter to be applied. Use any of the predefined filter flags. If omitted, FILTER_DEFAULT will be used

该函数在成功时返回所请求变量的值,如果过滤器失败则返回 false,如果未设置 var_name 变量则返回 null。

The function returns the value of the requested variable on success, false if the filter fails, or null if the var_name variable is not set.

Example

请看以下示例:

Take a look at the following example −

<?php
   if (!filter_input(INPUT_GET, "email", FILTER_VALIDATE_EMAIL)) {
      echo("Email is not valid");
   } else {
      echo("Email is valid");
   }
?>

它将生成以下 output

It will produce the following output

If you use the URL abc@example.com,

Email is valid
Email is not valid

你还可以针对通过 POST 方法接收的输入使用 INPUT_POST 类型 −

You can also use INPUT_POST type for validating the input received through the POST method −

<?php
   if (!filter_input(INPUT_POST, "email", FILTER_VALIDATE_EMAIL)) {
      echo("Email is not valid");
   } else {
      echo("Email is valid");
   }
?>

要使用 POST 请求传递数据,打开命令提示符,并使用以下 CURL 命令

To pass data with POST request, open the command prompt, and use the following CURL command

curl -X POST -d "{\"email\": \"a@b.com\"}" http://localhost/hello.php

filter_list() function

filter_list() 函数返回所有受支持的过滤器的列表

The filter_list() function returns a list of all supported filters

filter_list(): array

Example

该函数返回所有受支持的过滤器的名称数组,如果没有这样的过滤器,则返回空数组。

The function returns an array of names of all supported filters, empty array if there are no such filters.

<?php
   print_r(filter_list());
?>

它将生成以下 output

It will produce the following output

Array
(
   [0] => int
   [1] => boolean
   [2] => float
   [3] => validate_regexp
   [4] => validate_domain
   [5] => validate_url
   [6] => validate_email
   [7] => validate_ip
   [8] => validate_mac
   [9] => string
   [10] => stripped
   [11] => encoded
   [12] => special_chars
   [13] => full_special_chars
   [14] => unsafe_raw
   [15] => email
   [16] => url
   [17] => number_int
   [18] => number_float
   [19] => add_slashes
   [20] => callback
)

filter_input_array() function

filter_input_array() 获取外部变量,并可选地对其进行筛选。

The filter_input_array() gets external variables and optionally filters them.

filter_input_array(int $type, array|int $options = FILTER_DEFAULT,
   bool $add_empty = true): array|false|null

此函数用于在不重复调用 filter_input() 的情况下检索多个值。

This function is useful for retrieving many values without repetitively calling filter_input().

type 参数是 INPUT_GET、INPUT_POST、INPUT_COOKIE、INPUT_SERVER 或 INPUT_ENV 之一。

The type parameter is one of INPUT_GET, INPUT_POST, INPUT_COOKIE, INPUT_SERVER, or INPUT_ENV.

options 参数是用于定义参数的数组。有效键是包含变量名称的字符串,有效值是过滤器类型或选择性指定过滤器、标志和选项的数组。此参数也可以是用于保存过滤器常量的整数。然后输入数组中的所有值都将通过该过滤器进行筛选。

The options parameter is an array defining the arguments. A valid key is a string containing a variable name and a valid value is either a filter type, or an array optionally specifying the filter, flags and options. This parameter can be also an integer holding a filter constant. Then all values in the input array are filtered by this filter.

此函数在成功时返回一个包含请求变量值数组。如果由 type 指定的输入数组未填充,则在未给出 FILTER_NULL_ON_FAILURE 标志的情况下函数返回 null,否则返回 false。对于其他失败,则返回 false。

The function returns an array containing the values of the requested variables on success. If the input array designated by type is not populated, the function returns null if the FILTER_NULL_ON_FAILURE flag is not given, or false otherwise. For other failures, false is returned.

Example

要在 HTTP 请求中包含数组,我们在“hello.html”中使用以下 HTML 表单,并通过 POST 方法发送。

To include an array in the HTTP request, we use the following HTML form in "hello.html", and send it by POST method.

<!DOCTYPE html>
<html>
<body>
   <h1>Filter Input Array</h1>
   <form action="hello.php" method="POST">
      <p><label for="email">Enter your email:</label>
      <input type="text" id="email" name="email"></p>
      <p><label for="age">Enter your age<label>
      <input type = "text" id="age" name="age"></p>
      <input type="submit">
   </form>
</body>
</html>

验证输入数组的 PHP 脚本如下所示 −

The PHP script to validate the input array is as follows −

<?php
   $filters = array (
      "age" => array ("filter"=>FILTER_VALIDATE_INT,
         "options"=>array("min_range"=>20,"max_range"=>40) ),
      "email" => FILTER_VALIDATE_EMAIL
   );
   print_r(filter_input_array(INPUT_POST, $filters));
?>

打开 HTML 表单,并将年龄填为 30, * abc@example.com* 作为电子邮件,结果将是一个数组,验证这两个输入 −

Open the HTML form and enter 30 as age, abc@example.com as email, the result will be an array, validating both the inputs −

Array ( [age] => 30 [email] => abc@example.com )

尝试给出无效的输入,如“age=15”。输出数组将显示 age 密钥的 null 值

Try giving invalid inputs such as "age=15". The output array will show a null value for age key

Array ( [age] => [email] => abc@example.com )