PHP filters include two types
Validation: used to verify whether the verification item is legal
Sanitization: used to format the verified item, so it may modify the value of the verification item, delete illegal characters, etc.
input_filters_list()
is used to list all filters supported by the current system.
<?php 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
every 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, because they are the same filter, or two aliases of the same filter.
Filter data
Use the filter_var() method to filter the data. The following is a simple filtering example
<?php /*** 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
<?php /*** an integer to check ***/ $int = 'abc1234'; /*** validate the integer ***/ echo filter_var($int, FILTER_VALIDATE_INT); ?>
When running the code at this time, it is found that there is no variable output. This is because the $in variable has not passed verification, so this method returns bool (false). At the same time, it should be noted that even if $int=", bool (false) will be returned
Integer verification
The above several pieces of code simply verify whether a given value is an integer. In fact, FILTER_VALIDATE_INT also provides a numerical value Range verification, let’s verify a variable to determine whether it is an integer type, and verify whether its value is between 50 and 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 ?>
Run the above code and find that 42 is output, and no errors are found ,Why is this? When you want to add additional validation rules to the validation, you need to pass an array containing the 'options' key, as follows:
<?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))); ?>
Run the above code, the page will not have any output, because the above False is returned, indicating that the verification is successful.
You can also use this method to 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:
<?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 ?>
The above code will verify whether $int is an integer type value greater than (not including or equal to) $min. Run the code and output 12
Verify a set of variables
The above examples are simply verification of a single value. So what if you want to verify a set of variables? The answer is to use filter_var_array(). This function can verify multiple different types of data at the same time:
<?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 />'; } ?>
Run the above code and the output is as follows:
0 -- 10 1 -- 109 2 -- 3 -- -1234 4 -- 5 -- 6 -- Array
Octal and hexadecimal
FILTER_VALIDATE_INT filter supports both octal and hexadecimal. These two flags are:
FILTER_FLAG_ALLOW_HEX
FILTER_FLAG_ALLOW_OCTAL
Use an array to pass 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 validation FILTER_VALIDATE_B OOLEAN
<?php /*** test for a boolean value ***/ echo filter_var("true", FILTER_VALIDATE_BOOLEAN); //1 ?>
The code above Output 1, because the filter found a valid boolean value, other values that can return true are listed below
1
"1"
"yes"
"true"
"on"
TRUE
The following values will return false
0
"0"
"no"
"false"
"off"
""
NULL
FALSE
also supports the following usage
<?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 the above code, it is first judged that the in_array function is executed successfully and returns true, so the last code outputs 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 13 bool(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.php.cn"; /*** 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://php.cn)
FILTER_FLAG_HOST_REQUIRED – 要求 URL 包含主机名(比如:http://levi.php.cn)
FILTER_FLAG_PATH_REQUIRED – 要求 URL 在主机名后存在路径(比如:http://levi.php.cn/test/phpmailer/)
FILTER_FLAG_QUERY_REQUIRED – 要求 URL 存在查询字符串(比如:http://levi.php.cn/?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 = "someone@exa 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!