使用PHP自带的filter函数开展数据校验
使用PHP自带的filter函数进行数据校验
使用PHP自带的filter函数进行数据校验
Validation:用来验证验证项是否合法
Sanitization:用来格式化被验证的项目,因此它可能会修改验证项的值,将不合法的字符删除等。
参考PHP官方文档: Filter函数大全
参考来源: http://www.lai18.com/content/410997.html
input_filters_list()
用来列出当前系统所支持的所有过滤器。
<?phpforeach(filter_list() as $id => $filter){ echo $filter.' '.filter_id($filter)."\n";}?>
以上代码会输出如下信息
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
517
url
518
number_int
519
number_float
520
magic_quotes
521
callback
1024
每个过滤器都会拥有一个独自的ID。这里的每个过滤器都能够被filter_var()函数使用。下面将会逐个介绍其使用方法。注意 ,上面的string和strippedID相同,这是因为他们是同一个过滤器,或者说是同一个过滤器的两个别名罢了。
过滤数据
使用filter_var()方法对数据进行过滤,下面是一个简单的过滤例子
<?php /*** an integer to check ***/ $int = 1234; /*** validate the integer ***/ echo filter_var($int, FILTER_VALIDATE_INT); //1234?>
上面代码将会数据一个整数型的1234,因为$int变量通过的整数类型的验证,这次更换一下$int变量的内容
<?php /*** an integer to check ***/ $int = 'abc1234'; /*** validate the integer ***/ echo filter_var($int, FILTER_VALIDATE_INT);?>
此时在运行代码,发现没有任何变量输出,这是因为$in变量没有通过验证,因此这个方法返回bool(false)。同时也需要注意 一下,即使$int=”,也会返回bool(false)
整数验证
上面的几段代码简单的验证了一个给定值是否为整数的例子。其实FILTER_VALIDATE_INT也提供了数值范围的验证,下面我们 来验证一个变量,判断它是否为整数型,并验证它的值是否在50到100之间
<?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?>
运行上面的代码,发现42被输出来了,并没有发现任何错误,这是为什么啊?原来想要向验证中添加附加验证规则时候,需要传递一个含有’options‘键的数组,向下面这样:
<?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("options" => array("min_range" => $min, "max_range" => $max)));?>
运行上面的代码,页面不会有任何输出,因为上面返回了false,说明验证成功。
使用该方法也可以对负数进行范围验证
同时这种方式也支持单范围取值,即只是指定一个最大值或者最小值的范围,如:
<?php /*** an integer to check ***/ $int = 12; /*** lower limit of the int ***/ $min = 10; /*** validate the integer ***/ echo filter_var($int, FILTER_VALIDATE_INT,array('options' => array('min_range' => $min))); //12?>
上述代码会验证$int是否是大于(不包括等于)$min的整数类型的值,运行代码,输出12
对一组变量进行验证
上面的这些例子只是简单的对单个值进行验证,那么如果对一组变量进行验证呢?答案是使用filter_var_array()。该函数可以同时验证多个不同类型的数据。这里先做一个简单的例子:
<?php /*** an array of values to filter ***/ $arr = array(10,"109","", "-1234", "some text", "asdf234asdfgs", array()); /*** create an array of filtered values ***/ $filtered_array = filter_var_array($arr, FILTER_VALIDATE_INT); /*** print out the results ***/ foreach($filtered_array as $key => $value) { echo $key.' -- '.$value.'<br />'; }?>
运行上述代码,输出如下:
0 -- 101 -- 1092 -- 3 -- -12344 -- 5 -- 6 -- Array
八进制和十六进制
FILTER_VALIDATE_INT过滤器同时支持八进制和十六进制,这两种flags是:
FILTER_FLAG_ALLOW_HEX
FILTER_FLAG_ALLOW_OCTAL
利用数组传递flags
<?php /*** a hex value to check ***/ $hex = "0xff"; /*** filter with HEX flag ***/ echo filter_var($hex, FILTER_VALIDATE_INT, array("flags" => FILTER_FLAG_ALLOW_HEX)); //255?>
Boolean验证 FILTER_VALIDATE_BOOLEAN
<?php /*** test for a boolean value ***/ echo filter_var("true", FILTER_VALIDATE_BOOLEAN); //1?>
上面的代码输出1,因为过滤器发现了一个有效的布尔值,下面列出了其它可以返回true的值
1
“1”
“yes”
“true”
“on”
TRUE
下列值将会返回false
0
“0”
“no”
“false”
“off”
“”
NULL
FALSE
同时也支持下面的用法
<?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) }}
浮点型验证 FILTER_VALIDATE_FLOAT
<?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"; }?>
对数组进行浮点型验证
同其它验证一样,也可以对一个数组进行浮点型验证。与boolean验证类似,提供一个flgs FILTER_REQUIRE_ARRAY。
<?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);?>
上面的代码输出如下
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) { }}
浮点型过滤器支持我们指定一个数字间的分隔符
<?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); }?>
在上面的代码中,$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 13bool(false)bool(false)
验证URL FILTER_VALIDATE_URL
URL的验证是一项很困难的行为,由于URL的不确定性,它没有最大长度的限制,而且它的格式是多样化的,你可以通过阅读RFC 1738来了解有关URL的一些信息。之后你可以创建一个类来验证所有ipv4和ipv6的URL,以及一些其它URL的验证。你也可以简单的使用FILTER_VALIDATE_URL来验证URL。
<?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 />"; }?>
上面的例子中通过简单的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)
<?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!"; }?>
可以发现,上面的代码没有通过验证
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 过滤器把值作为电子邮件地址来验证。
<?php $email = "[email protected] mple.com"; if(!filter_var($email, FILTER_VALIDATE_EMAIL)) { echo "E-mail is not valid"; } else { echo "E-mail is valid"; }?>
自定义过滤器 FILTER_CALLBACK
FILTER_CALLBACK 过滤器使用用户自定义函数对值进行过滤。
这个过滤器为我们提供了对数据过滤的完全控制。
指定的函数必须存入名为 “options” 的关联数组中。
<?php function convertSpace($string) { return str_replace(" ", "_", $string); } $string = "Peter is a great guy!"; echo filter_var($string, FILTER_CALLBACK,array("options" => "convertSpace"));?>
输出
Peter_is_a_great_guy!
- 1楼u0112524023小时前
- thanks

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

The validate function is typically used to validate and check input data to ensure that it conforms to specific rules, formats, or conditions. Its function is to verify the legality of input data in the program to improve the accuracy, integrity and security of the data. By using the validate function, invalid or illegal data can be detected and intercepted in advance to avoid subsequent code processing errors or exceptions.

Title: Example of using the Array.Sort function to sort an array in C# Text: In C#, array is a commonly used data structure, and it is often necessary to sort the array. C# provides the Array class, which has the Sort method to conveniently sort arrays. This article will demonstrate how to use the Array.Sort function in C# to sort an array and provide specific code examples. First, we need to understand the basic usage of the Array.Sort function. Array.So
![How to solve the '[Vue warn]: Failed to resolve filter' error](https://img.php.cn/upload/article/000/887/227/169243040583797.jpg?x-oss-process=image/resize,m_fill,h_207,w_330)
Methods to solve the "[Vuewarn]:Failedtoresolvefilter" error During the development process using Vue, we sometimes encounter an error message: "[Vuewarn]:Failedtoresolvefilter". This error message usually occurs when we use an undefined filter in the template. This article explains how to resolve this error and gives corresponding code examples. When we are in Vue

In PHP, there are many powerful array functions that can make array operations more convenient and faster. When we need to combine two arrays into an associative array, we can use PHP's array_combine function to achieve this operation. This function is actually used to combine the keys of one array as the values of another array into a new associative array. Next, we will explain how to use the array_combine function in PHP to combine two arrays into an associative array. Learn about array_comb

When programming in PHP, we often need to merge arrays. PHP provides the array_merge() function to complete array merging, but when the same key exists in the array, this function will overwrite the original value. In order to solve this problem, PHP also provides an array_merge_recursive() function in the language, which can merge arrays and retain the values of the same keys, making the program design more flexible. array_merge

php提交表单通过后,弹出的对话框怎样在当前页弹出php提交表单通过后,弹出的对话框怎样在当前页弹出而不是在空白页弹出?想实现这样的效果:而不是空白页弹出:------解决方案--------------------如果你的验证用PHP在后端,那么就用Ajax;仅供参考:HTML code

In PHP programming, array is a very important data structure that can handle large amounts of data easily. PHP provides many array-related functions, array_fill() is one of them. This article will introduce in detail the usage of the array_fill() function, as well as some tips in practical applications. 1. Overview of the array_fill() function The function of the array_fill() function is to create an array of a specified length and composed of the same values. Specifically, the syntax of this function is

First define a Filter for unified access URL interception. The code is as follows: publicclassUrlFilterimplementsFilter{privateLoggerlog=LoggerFactory.getLogger(UrlFilter.class);@OverridepublicvoiddoFilter(ServletRequestrequest,ServletResponseresponse,FilterChainchain)throwsIOException,ServletException{H
