Home > Backend Development > PHP Tutorial > Detailed explanation of the method of filter function verifying data in PHP_php skills

Detailed explanation of the method of filter function verifying data in PHP_php skills

WBOY
Release: 2016-05-16 20:09:17
Original
1205 people have browsed it

Introducing the detailed method of verifying data by the filter function in PHP. PHP filters include two types: Validation is used to verify whether the verification item is legal
, Sanitization is used to format the items being verified, so it may modify the value of the verification item and delete illegal characters.

input_filters_list()

is used to list all filters supported by the current system.

Copy code The code is as follows:

foreach(filter_list() as $id => $filter)
{
echo $filter.' '.filter_id($filter)."n";
}
?>

The above code will output the following information

Filter Name Filter ID
int 257
boolean 258
float 259
validate_regexp 272
validate_url 273
validate_email 274
validate_ip 275
string 513
stripped 513
encoded 514
special_chars 515
full_special_chars 522
unsafe_raw 516
email 517
url 518
number_int 519
number_float 520
magic_quotes 521
callback 1024
Copy after login

Each filter will have a unique ID. Each filter here can be used by the filter_var() function. The following will introduce its use one by one. Note that the above string and strippedID are the same. This is because they are the same filter, or they are just two aliases of the same filter.

Filter data

Use the filter_var() method to filter data. The following is a simple filtering example

Copy code The code is as follows:

/*** an integer to check ***/
$int = 1234;
/*** validate the integer ***/
echo filter_var($int, FILTER_VALIDATE_INT);
//1234
?>

The above code will data an integer type 1234, because the $int variable passes the integer type verification, this time change the content of the $int variable

Copy code The code is as follows:

/*** an integer to check ***/
$int = 'abc1234';

/*** validate the integer ***/
echo filter_var($int, FILTER_VALIDATE_INT);
?>

When I run the code at this time, I find that no variables are output. This is because the $in variable does not pass verification, so this method returns bool (false). At the same time, please note that even if $int=", bool(false)

will be returned.

Integer validation

The above code snippets simply verify whether a given value is an integer. In fact, FILTER_VALIDATE_INT also provides verification of the numerical range. Let's verify a variable to determine whether it is an integer type, and verify whether its value is between 50 and 100

<&#63;php
  /*** an integer to check ***/
  $int = 42;

  /*** lower limit of the int ***/
  $min = 50;

  /*** upper limit of the int ***/
  $max = 100;

  /*** validate the integer ***/
  echo filter_var($int, FILTER_VALIDATE_INT, array("min_range" => $min, "max_range" => $max));
  //42
&#63;>

Copy after login

Run the above code and find that 42 is output, but no errors are found. Why is this? It turns out that when you want to add additional validation rules to validation, you need to pass an array containing the 'options' key, as follows:

Copy code The code is as follows:

/*** an integer to check ***/
$int = 42;

/*** lower limit of the int ***/
$min = 50;

/*** upper limit of the int ***/
$max = 100;

/*** validate the integer ***/
echo filter_var($int, FILTER_VALIDATE_INT, array("options" => array("min_range" => $min, "max_range" => $max)));
?>

Run the above code, the page will not produce any output, because the above returns false, indicating that the verification is successful.

Using this method, you can also perform range verification on negative numbers
At the same time, this method also supports single-range values, that is, just specify a range of maximum or minimum values, such as:

Copy code The code is as follows:

/*** 확인할 정수 ***/
$int = 12;

/*** 정수의 하한 ***/
$분 = 10;

/*** 정수 유효성 검사 ***/
echo filter_var($int, FILTER_VALIDATE_INT,array('options' => array('min_range' => $min)));
//12
?>

위 코드는 $int가 $min보다 큰(배타적으로 동일한) 정수 유형 값인지 확인하고 12를 출력합니다.

변수 집합 유효성 검사

위의 예는 단순히 단일 값의 유효성을 검사하는 것이므로 변수 집합의 유효성을 검사하면 어떻게 될까요? 대답은 filter_var_array()를 사용하는 것입니다. 이 기능은 동시에 여러 가지 유형의 데이터를 확인할 수 있습니다. 다음은 간단한 예입니다.

코드 복사 코드는 다음과 같습니다.

/*** 필터링할 값의 배열 ***/
$arr = array(10,"109","", "-1234", "일부 텍스트", "asdf234asdfgs", array());

/*** 필터링된 값의 배열 생성 ***/
$filtered_array = filter_var_array($arr, FILTER_VALIDATE_INT);

/*** 결과를 인쇄하세요 ***/
foreach($filtered_array as $key => $value)
{
echo $key.' -- '.$value.'
';
}
?>

위 코드를 실행하면 다음과 같이 출력됩니다.

코드 복사 코드는 다음과 같습니다.

0 - 10
1 -- 109
2 --
3 -- -1234
4 --
5 --
6 -- 배열

8진수와 16진수

FILTER_VALIDATE_INT 필터는 8진수와 16진수를 모두 지원합니다.

FILTER_FLAG_ALLOW_HEX
FILTER_FLAG_ALLOW_OCTAL

배열을 사용하여 플래그 전달

코드 복사 코드는 다음과 같습니다.

/*** 확인할 16진수 값 ***/
$hex = "0xff";

/*** HEX 플래그를 사용한 필터 ***/
echo filter_var($hex, FILTER_VALIDATE_INT, array("flags" => FILTER_FLAG_ALLOW_HEX));
//255
?>

부울 유효성 검사 FILTER_VALIDATE_BOOLEAN

코드 복사 코드는 다음과 같습니다.

/*** 부울 값 테스트 ***/
echo filter_var("true", FILTER_VALIDATE_BOOLEAN);
//1
?>

위 코드는 필터가 유효한 부울 값을 찾았기 때문에 1을 출력합니다. true를 반환할 수 있는 다른 값은 아래에 나열되어 있습니다.

코드 복사 코드는 다음과 같습니다.

1
"1"
"네"
"사실"
“켜짐”

다음 값은 false를 반환합니다

코드 복사 코드는 다음과 같습니다.

0
"0"
"아니요"
"거짓"
"꺼져"
""
NULL
거짓

다음 사용법도 지원합니다

코드 복사 코드는 다음과 같습니다.

<?php
/*** a simple array ***/
$array = array(1,2,3,4,5);

/*** test for a boolean value ***/
echo filter_var(in_array(3, $array), FILTER_VALIDATE_BOOLEAN) ? "TRUE" : "FALSE";
//true
?>

在上面的代码中,先判断了in_array函数执行成功,返回了true,所以最后这段代码输出true

我们也可以传递一个数组,来判断数组中值的boolean类型

复制代码 代码如下:

<?php
/*** a multi dimensional array ***/
$array = array(0, 1, 2, 3, 4, array(0, 1, 2, 3, 4));

/*** create the list of values ***/
$values = filter_var($array, FILTER_VALIDATE_BOOLEAN, FILTER_REQUIRE_ARRAY);

/*** dump the values ***/
var_dump($values);
?>

上面代码输出如下:

array(6) {
  [0] => bool(false)
  [1] => bool(true)
  [2] => bool(false)
  [3] => bool(false)
  [4] => bool(false)
  [5] => array(5) {
    [0] => bool(false)
    [1] => bool(true)
    [2] => bool(false)
    [3] => bool(false)
    [4] => bool(false)
  }
}
Copy after login

浮点型验证 FILTER_VALIDATE_FLOAT

<&#63;php
  /*** an FLOAT value to check ***/
  $float = 22.42;

  /*** validate with the FLOAT flag ***/
  if(filter_var($float, FILTER_VALIDATE_FLOAT) === false)
  {
    echo "$float is not valid!";
  }
  else
  {
    echo "$float is a valid floating point number";
  }
&#63;>

Copy after login

对数组进行浮点型验证

同其它验证一样,也可以对一个数组进行浮点型验证。与boolean验证类似,提供一个flgs FILTER_REQUIRE_ARRAY。

<&#63;php
  /*** an array of values ***/
  $array = array(1.2,"1.7","", "-12345.678", "some text", "abcd4.2efgh", array());

  /*** validate the array ***/
  $validation_array = filter_var($array, FILTER_VALIDATE_FLOAT, FILTER_REQUIRE_ARRAY);

  /*** dump the array of validated data ***/
  var_dump($validation_array);
&#63;>

Copy after login

上面的代码输出如下

array(7) {
  [0] => float(1.2)
  [1] => float(1.7)
  [2] => bool(false)
  [3] => float(-23234.123)
  [4] => bool(false)
  [5] => bool(false)
  [6] => array(0) { }
}
Copy after login

浮点型过滤器支持我们指定一个数字间的分隔符

<&#63;php
  /*** an array of floats with seperators ***/
  $floats = array(
    "1,234" => ",",
    "1.234" => "..",
    "1.2e3" => ","
  );

  /*** validate the floats against the user defined decimal seperators ***/
  foreach ($floats as $float => $dec_sep)
  {
    $out = filter_var($float, FILTER_VALIDATE_FLOAT, array("options" => array("decimal" => $dec_sep)));

    /*** dump the results ***/
    var_dump($out);
  }
&#63;>

Copy after login

在上面的代码中,$floats函数中第一个元素值为',',所以在判断1,234值时为其指定了分隔符为',',所以返回true
上面代码完整返回值

复制代码 代码如下:

float(1.234)
Warning: filter_var() [function.filter-var]: decimal separator must be one char in /www/filter.php on line 13
bool(false)
bool(false)

验证URL FILTER_VALIDATE_URL

URL的验证是一项很困难的行为,由于URL的不确定性,它没有最大长度的限制,而且它的格式是多样化的,你可以通过阅读RFC 1738来了解有关URL的一些信息。之后你可以创建一个类来验证所有ipv4和ipv6的URL,以及一些其它URL的验证。你也可以简单的使用FILTER_VALIDATE_URL来验证URL。

<&#63;php
   /*** a rfc compliant web address ***/
  $url = "http://www.phpro.org";

  /*** try to validate the URL ***/
  if(filter_var($url, FILTER_VALIDATE_URL) === FALSE)
  {
    /*** if there is no match ***/
    echo "Sorry, $url is not valid!";
  }
  else
  {
    /*** if we match the pattern ***/
    echo "The URL, $url is valid!<br />";
  }
&#63;>

Copy after login

上面的例子中通过简单的if语句来判断给定的URL是否合法,但并不是所有的URL都是这样的格式。有时候URL可是能是一个IP地址,也可能在URL中传递了多个参数。下面提供了几个flags来帮助我们验证URL:

FILTER_FLAG_SCHEME_REQUIRED – 要求 URL 是 RFC 兼容 URL。(比如:http://cg.am
FILTER_FLAG_HOST_REQUIRED – 要求 URL 包含主机名(比如:
http://levi.cg.com
FILTER_FLAG_PATH_REQUIRED – 要求 URL 在主机名后存在路径(比如:
http://levi.cg.am/test/phpmailer/
FILTER_FLAG_QUERY_REQUIRED – 要求 URL 存在查询字符串(比如:
http://levi.cg.am/?p=2618

<&#63;php
  /*** a non rfc compliant URL ***/
  $url = "index.php";

  /*** try to validate the URL ***/
  if(filter_var($url, FILTER_VALIDATE_URL, FILTER_FLAG_SCHEME_REQUIRED) === FALSE)
  {
    /*** if there is no match ***/
    echo "Sorry, $url is not valid!";
  }
  else
  {
    /*** if the URL is valid ***/
    echo "The URL, $url is valid!";
  }
&#63;>

Copy after login

可以发现,上面的代码没有通过验证

IP过滤器 FILTER_VALIDATE_IP

FILTER_VALIDATE_IP 过滤器把值作为 IP 进行验证。
Name: “validate_ip”
ID-number: 275

可能的标志:

FILTER_FLAG_IPV4 – 要求值是合法的 IPv4 IP(比如:255.255.255.255)
FILTER_FLAG_IPV6 – 要求值是合法的 IPv6 IP(比如:2001:0db8:85a3:08d3:1319:8a2e:0370:7334)
FILTER_FLAG_NO_PRIV_RANGE – 要求值是 RFC 指定的私域 IP (比如 192.168.0.1)
FILTER_FLAG_NO_RES_RANGE – 要求值不在保留的 IP 范围内。该标志接受 IPV4 和 IPV6 值。
Email过滤器FILTER_VALIDATE_EMAIL

FILTER_VALIDATE_EMAIL 过滤器把值作为电子邮件地址来验证。

<&#63;php
  $email = "someone@exa mple.com";

  if(!filter_var($email, FILTER_VALIDATE_EMAIL))
  {
    echo "E-mail is not valid";
  }
  else
  {
    echo "E-mail is valid";
  }
&#63;>

Copy after login
Copy after login

自定义过滤器 FILTER_CALLBACK

FILTER_CALLBACK 过滤器使用用户自定义函数对值进行过滤。

这个过滤器为我们提供了对数据过滤的完全控制。

指定的函数必须存入名为 “options” 的关联数组中。

<&#63;php
  $email = "someone@exa mple.com";

  if(!filter_var($email, FILTER_VALIDATE_EMAIL))
  {
    echo "E-mail is not valid";
  }
  else
  {
    echo "E-mail is valid";
  }
&#63;>

Copy after login
Copy after login

输出

复制代码 代码如下:

Peter_is_a_great_guy!

以上所述就是本文全部内容,希望大家喜欢。

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