php filter(一)

Jun 23, 2016 pm 02:35 PM

PHP过滤器包含两种类型
Validation:用来验证验证项是否合法
Sanitization:用来格式化被验证的项目,因此它可能会修改验证项的值,将不合法的字符删除等。


input_filters_list()函数用来列出当前系统所支持的所有过滤器。

1 <table>2 <tr><td>Filter Name</td><td>Filter ID</td></tr>3 <?php4 foreach(filter_list() as $id =>$filter)5 {6     echo '<tr><td>'.$filter.'</td><td>'.filter_id($filter).'</td></tr>'."\n";7 }8 ?>9 </table>
Copy after login

以上代码会输出如下信息
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
unsafe_raw 516
email 517
url 518
number_int 519
number_float 520
magic_quotes 521
callback 1024
每个过滤器都会拥有一个独自的ID。这里的每个过滤器都能够被filter_var()函数使用。下面将会逐个介绍其使用方法。注意 ,上面的string和strippedID相同,这是因为他们是同一个过滤器,或者说是同一个过滤器的两个别名罢了。
过滤数据
使用filter_var()方法对数据进行过滤,下面是一个简单的过滤例子

1 <?php2 3 /*** an integer to check ***/4 $int = 1234;5 /*** validate the integer ***/6 echo filter_var($int, FILTER_VALIDATE_INT);7 //12348 ?>
Copy after login

上面代码将会数据一个整数型的1234,因为$int变量通过的整数类型的验证,这次更换一下$int变量的内容

1 <?php2 3 /*** an integer to check ***/4 $int = 'abc1234';5 /*** validate the integer ***/6 echo filter_var($int, FILTER_VALIDATE_INT);7 8 ?>
Copy after login

此时在运行代码,发现没有任何变量输出,这是因为$in变量没有通过验证,因此这个方法返回bool(false)。同时也需要注意 一下,即使$int='',也会返回bool(false)

整数验证
上面的几段代码简单的验证了一个给定值是否为整数的例子。其实FILTER_VALIDATE_INT也提供了数值范围的验证,下面我们 来验证一个变量,判断它是否为整数型,并验证它的值是否在50到100之间

 1 <?php 2 /*** an integer to check ***/ 3 $int = 42; 4 /*** lower limit of the int ***/ 5 $min = 50; 6 /*** upper limit of the int ***/ 7 $max = 100; 8  9 /*** validate the integer ***/10 echo filter_var($int, FILTER_VALIDATE_INT, array("min_range"=>$min, "max_range"=>$max));11 //4212 ?>
Copy after login

运行上面的代码,发现42被输出来了,并没有发现任何错误,这是为什么啊?原来想要向验证中添加附加验证规则时候,需要传递一个含有'options'键的数组,向下面这样:

 1 <?php 2 /*** an integer to check ***/ 3 $int = 42; 4 /*** lower limit of the int ***/ 5 $min = 50; 6 /*** upper limit of the int ***/ 7 $max = 100; 8  9 /*** validate the integer ***/10 echo filter_var($int, FILTER_VALIDATE_INT, array("options" => array("min_range"=>$min, "max_range"=>$max)));11 12 ?>
Copy after login

运行上面的代码,页面不会有任何输出,因为上面返回了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?>
Copy after login

上述代码会验证$int是否是大于(不包括等于)$min的整数类型的值,运行代码,输出12
上面的这些例子只是简单的对单个值进行验证,那么如果对一组变量进行验证呢?答案是使用filter_var_array()。该函数可以同时验证多个不同类型的数据。这里先做一个简单的例子

 1 <?php 2  3 /*** an array of values to filter ***/ 4 $arr = array(10,"109","", "-1234", "some text", "asdf234asdfgs", array()); 5  6 /*** create an array of filtered values ***/ 7 $filtered_array = filter_var_array($arr, FILTER_VALIDATE_INT); 8  9 /*** print out the results ***/10 foreach($filtered_array as $key=>$value)11 {12     echo $key.' -- '.$value.'<br />';13 }14 ?>
Copy after login

运行上述代码,输出如下
0 -- 10
1 -- 109
2 --
3 -- -1234
4 --
5 --
6 -- Array
FILTER_VALIDATE_INT过滤器同时支持八进制和十六进制,这两种flags是
FILTER_FLAG_ALLOW_HEX
FILTER_FLAG_ALLOW_OCTAL
利用数组传递flags

1 <?php2 3 /*** a hex value to check ***/4 $hex = "0xff";5 6 /*** filter with HEX flag ***/7 echo filter_var($hex, FILTER_VALIDATE_INT, array("flags"=>FILTER_FLAG_ALLOW_HEX));8 //2559 ?>
Copy after login

 

 PHP技术交流群 170855791

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

Describe the SOLID principles and how they apply to PHP development. Describe the SOLID principles and how they apply to PHP development. Apr 03, 2025 am 12:04 AM

The application of SOLID principle in PHP development includes: 1. Single responsibility principle (SRP): Each class is responsible for only one function. 2. Open and close principle (OCP): Changes are achieved through extension rather than modification. 3. Lisch's Substitution Principle (LSP): Subclasses can replace base classes without affecting program accuracy. 4. Interface isolation principle (ISP): Use fine-grained interfaces to avoid dependencies and unused methods. 5. Dependency inversion principle (DIP): High and low-level modules rely on abstraction and are implemented through dependency injection.

Explain the concept of late static binding in PHP. Explain the concept of late static binding in PHP. Mar 21, 2025 pm 01:33 PM

Article discusses late static binding (LSB) in PHP, introduced in PHP 5.3, allowing runtime resolution of static method calls for more flexible inheritance.Main issue: LSB vs. traditional polymorphism; LSB's practical applications and potential perfo

How to automatically set permissions of unixsocket after system restart? How to automatically set permissions of unixsocket after system restart? Mar 31, 2025 pm 11:54 PM

How to automatically set the permissions of unixsocket after the system restarts. Every time the system restarts, we need to execute the following command to modify the permissions of unixsocket: sudo...

How to debug CLI mode in PHPStorm? How to debug CLI mode in PHPStorm? Apr 01, 2025 pm 02:57 PM

How to debug CLI mode in PHPStorm? When developing with PHPStorm, sometimes we need to debug PHP in command line interface (CLI) mode...

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

How to send a POST request containing JSON data using PHP's cURL library? How to send a POST request containing JSON data using PHP's cURL library? Apr 01, 2025 pm 03:12 PM

Sending JSON data using PHP's cURL library In PHP development, it is often necessary to interact with external APIs. One of the common ways is to use cURL library to send POST�...

See all articles