search
HomeBackend DevelopmentPHP Tutorialphp 过滤器实现代码_php技巧

在以前,一个用户通过网络主要是获取信息。而如今的网络刚更注重与用户的交互,用户不再仅仅是网站的浏览者,也是网站内容的制造者。由以前单纯的“读”向“写”以及“共同创作”发展,由被动接收信息向主动分行信息发展。而随之而来的安全问题也成了web开发者不可忽视的问题,验证第三方来源的数据成了每个web程序必不可少的功能。

在以前,PHP需要验证数据,一般都是程序员自己通过正则表达式实现,而从PHP从5.2开始把原本的PCEL中的filter函数移到了内置库中,并做了不少强化,可以用这些函数实现对数据的过滤和验证。

数据来源及验证类型
PHP中的数据来源包含两部分,其一是外部变量(如POST、GET、COOKIE等),还有一种是页面内部产生的数据。PHP针对这两种数据类型分别定义了ilter_input_**和filter_var_**系列函数。而依据验证方法的不一样又可以分为Validating和Sanitizing两种。Validating用于验证数据,返回一个布尔值。Sanitizing则按规则过滤一些特定的字符,返回的是处理后的字符串。

简单用法
比如验证一个字符串是否是一个整数,在以往我们可以通过正则表达式或是is_numeric函数实现:

复制代码 代码如下:

$str = '51ab';
preg_match('/^[0-9]*$/', $str);
is_numeric($str);

新的验证函数可以用以下方式:

$str = '51ab';
echo filter_var($str, FILTER_VALIDATE_INT) ? 'is valid' : 'is not valid';FILTER_VALIDATE_INT是PHP定义的一个过滤器,用于验证$str是否为一个整数。实际上这就是一个数值常量,通过echo FILTER_VALIDATE_INT;发现值为257。所以我们也可以用:

$str = '51ab';
echo filter_var($str, 257) ? 'is valid' : 'is not valid';PHP中定义了大量常用的过滤器,我们可以通过filter_list()获得所有支持的过滤器名称(用字符串表示),然后再用filter_id(string)获取其数值:

print_r(filter_list()); // 所有支持的过滤器名称。
echo '=========';
echo filter_id('int'); // 'int' 是filter_list返回的一个过滤器名称。以上将输入出类似以下内容:

array(0=>int',1=>'boolean',2=>'float',3=>'validate_regexp')
==========
257Sanitizing过滤器
上面这个是验证数据格式是否正确,有时候过滤掉无关的内容也是挺重要的。SANITIZE过滤提供了这种功能,比如过滤掉一个email中多余的字符:

$email = '<script>alert("test");xxx@caixw.com'; <BR>echo $email; // 直接输出,将会执行script脚本。 <BR>echo filter_var($email, FILTER_SANITIZE_EMAIL); // 会过滤掉<和>输出scriptalerttestscriptxxx@caixw.com选项和标志 <BR>filter_var的功能还不止于此,还可以指定第三个参数,附加一些特殊的选项,比如一个规定了最大值的整数: <BR><div class="codetitle"><span><a style="CURSOR: pointer" data="53354" class="copybut" id="copybut53354" onclick="doCopy('code53354')"><U>复制代码 代码如下:<div class="codebody" id="code53354"> <BR>$options = array( <BR>'options'=>array('max_range'=>50), <BR>'flags'=>FILTER_FLAG_ALLOW_OCTAL, <BR>); <BR>$str = '51'; <BR>echo filter_var($str, FILTER_VALIDATE_INT, $options) ? 'is valid' : 'is not valid'; <BR> <BR>上面将返回is not valid。因为max_range规定其最大值只能为50。而FILTER_FLAG_ALLOW_OCTAL则允许验证的数据是一个八进制的,也即是0开头的。 <br><br>$options参数是一个数组,包含两个元素:options和flags。若是只有flags元素,则也可以直接传递而不用数组。 <br><br>验证外部数据 <BR>除了PHP脚本自己产生的数据,来自用户提交的数据占大部分。当然我们也可以直接用filter_var进行过滤: <BR><div class="codetitle"><span><a style="CURSOR: pointer" data="31328" class="copybut" id="copybut31328" onclick="doCopy('code31328')"><U>复制代码 代码如下:<div class="codebody" id="code31328"> <BR>if(isset($_GET['age'])) <BR>{ <BR>echo filter_var($_GET['age'], FILTER_VALIDATE_INT) ? 'is valid' : 'is not valid'; <BR>} <BR> <BR>但是PHP中还专门提供了几个函数用于验证外部来源的数据: <BR><div class="codetitle"><span><a style="CURSOR: pointer" data="70849" class="copybut" id="copybut70849" onclick="doCopy('code70849')"><U>复制代码 代码如下:<div class="codebody" id="code70849"> <BR>if(filter_has_var(INPUT_GET, 'age')) <BR>{ <BR>echo filter_input(INPUT_GET, 'age', FILTER_VALIDATE_INT) ? 'is valid' : 'is not valid'; <BR>} <BR> <BR>相较于filter_var,filter_input多了一个参数(第一个参数)用于指定数据的来源。而filter_has_var()而用来判断是否存在指定的数据。 <br><br>一次过滤多个数据 <BR>PHP还提供了filter_var_array和filter_input_array函数用于一次性验证多个数据。 <br><br>这是来自php.net上的一个实例,用于说明filter_var_array()怎么使用。 <BR><div class="codetitle"><span><a style="CURSOR: pointer" data="52286" class="copybut" id="copybut52286" onclick="doCopy('code52286')"><U>复制代码 代码如下:<div class="codebody" id="code52286"> <BR>$data = array( <BR>'product_id' => 'libgd<script>', <BR>'component' => '10', <BR>'versions' => '2.0.33', <BR>'testscalar' => array('2', '23', '10', '12'), <BR>'testarray' => '2', <BR>); <br><br>$args = array( <BR>'product_id' => FILTER_SANITIZE_ENCODED, <BR>'component' => array('filter' => FILTER_VALIDATE_INT, <BR>'flags' => FILTER_FORCE_ARRAY, <BR>'options' => array('min_range' => 1, 'max_range' => 10) <BR>), <BR>'versions' => FILTER_SANITIZE_ENCODED, <BR>'doesnotexist' => FILTER_VALIDATE_INT, <BR>'testscalar' => array( <BR>'filter' => FILTER_VALIDATE_INT, <BR>'flags' => FILTER_REQUIRE_SCALAR, <BR>), <BR>'testarray' => array( <BR>'filter' => FILTER_VALIDATE_INT, <BR>'flags' => FILTER_FORCE_ARRAY, <BR>) <BR>); <BR>$myinputs = filter_var_array($data, $args); <BR> <BR>自定义过滤器 <BR>可以通过传递一个特殊的过滤器FILTER_CALLBACK来指定一个自定义的过滤器,下面这个过滤器将把所有邮箱地址的@转换成#。 <BR><div class="codetitle"><span><a style="CURSOR: pointer" data="34532" class="copybut" id="copybut34532" onclick="doCopy('code34532')"><U>复制代码 代码如下:<div class="codebody" id="code34532"> <BR>function fun($value) <BR>{ <BR>return strtr($value,'@','#'); <BR>} <BR>$var = filter_var('abc@caixw.com', FILTER_CALLBACK, array('options' => 'fun')); <BR>echo $var; <BR><BR> <H3>其它 <TABLE border=1> <THEAD> <TR> <TH>ID<BR>(过滤器常量) <TH>名称<BR>(filter_list()函数返回的名称) <TH>可用选项 <TH>标志位 <TH>描述 <TBODY> <TR> <TH colSpan=5>Validating <TR> <TD>FILTER_VALIDATE_BOOLEAN <TD>"boolean" <TD> <TD>FILTER_NULL_ON_FAILURE <TD>当难的数据为"1","true","on","yes"时返回true,否则返回false。当设置了FILTER_NULL_ON_FAILURE标志位,则仅在值是"0","false","off","no", 和""是返回false,其它非true值返回null。 <TR> <TD>FILTER_VALIDATE_EMAIL <TD>"validate_email" <TD> <TD> <TD>验证邮箱 <TR> <TD>FILTER_VALIDATE_FLOAT <TD>"float" <TD>decimal <TD>FILTER_FLAG_ALLOW_THOUSAND <TD>验证浮点数 <TR> <TD>FILTER_VALIDATE_INT <TD>"int" <TD>min_range, max_range <TD>FILTER_FLAG_ALLOW_OCTAL, FILTER_FLAG_ALLOW_HEX <TD>验证一个指定范围内的整数值 <TR> <TD>FILTER_VALIDATE_IP <TD>"validate_ip" <TD> <TD>FILTER_FLAG_IPV4, FILTER_FLAG_IPV6, FILTER_FLAG_NO_PRIV_RANGE, FILTER_FLAG_NO_RES_RANGE <TD>验证IP地址 <TR> <TD>FILTER_VALIDATE_REGEXP <TD>"validate_regexp" <TD>regexp <TD> <TD>验证一个正则表达式 <TR> <TD>FILTER_VALIDATE_URL <TD>"validate_url" <TD> <TD>FILTER_FLAG_PATH_REQUIRED, FILTER_FLAG_QUERY_REQUIRED <TD>验证一个URL <TR> <TH colSpan=5>Sanitizing <TR> <TD>FILTER_SANITIZE_EMAIL <TD>"email" <TD> <TD> <TD>移除除英文字符,数字以及!#$%&'*+-/=?^_`{|}~@.[]之外的字符。 <TR> <TD>FILTER_SANITIZE_ENCODED <TD>"encoded" <TD> <TD>FILTER_FLAG_STRIP_LOW, FILTER_FLAG_STRIP_HIGH, FILTER_FLAG_ENCODE_LOW, FILTER_FLAG_ENCODE_HIGH <TD>URL编码字符串,去除或编码指定字符串。 <TR> <TD>FILTER_SANITIZE_MAGIC_QUOTES <TD>"magic_quotes" <TD> <TD> <TD>应用 addslashes()函数 <TR> <TD>FILTER_SANITIZE_NUMBER_FLOAT <TD>"number_float" <TD> <TD>FILTER_FLAG_ALLOW_FRACTION, FILTER_FLAG_ALLOW_THOUSAND, FILTER_FLAG_ALLOW_SCIENTIFIC <TD>移除除数字,+-以及.,eE以外的字符 <TR> <TD>FILTER_SANITIZE_NUMBER_INT <TD>"number_int" <TD> <TD> <TD>移除除数字以及+-以外的字符 <TR> <TD>FILTER_SANITIZE_SPECIAL_CHARS <TD>"special_chars" <TD> <TD>FILTER_FLAG_STRIP_LOW, FILTER_FLAG_STRIP_HIGH, FILTER_FLAG_ENCODE_HIGH <TD>HTML转义字符,'"&><以及 ASCII 值小于 32 的字符。以及其它指定的字符。 <TR> <TD>FILTER_SANITIZE_STRING <TD>"string" <TD> <TD>FILTER_FLAG_NO_ENCODE_QUOTES, FILTER_FLAG_STRIP_LOW, FILTER_FLAG_STRIP_HIGH, FILTER_FLAG_ENCODE_LOW, FILTER_FLAG_ENCODE_HIGH, FILTER_FLAG_ENCODE_AMP <TD>去除标签,或是去除或编码指定的字符。 <TR> <TD>FILTER_SANITIZE_STRIPPED <TD>"stripped" <TD> <TD> <TD>Alias of "string" filter. <TR> <TD>FILTER_SANITIZE_URL <TD>"url" <TD> <TD> <TD>删除所有字符除字母、数字以及$-_.+!*'(),{}|\\^~[]`<>#%";/?:@&= <TR> <TD>FILTER_UNSAFE_RAW <TD>"unsafe_raw" <TD> <TD>FILTER_FLAG_STRIP_LOW, FILTER_FLAG_STRIP_HIGH, FILTER_FLAG_ENCODE_LOW, FILTER_FLAG_ENCODE_HIGH, FILTER_FLAG_ENCODE_AMP <TD>不做任何改变,或是按标志位去除或是编码指定字母。 <TR> <TD>FILTER_CALLBACK <TD>"callback" <TD> <TD>FILTER_FLAG_STRIP_LOW, FILTER_FLAG_STRIP_HIGH, FILTER_FLAG_ENCODE_LOW, FILTER_FLAG_ENCODE_HIGH, FILTER_FLAG_ENCODE_AMP <TD>自定义过滤器 <H4>标志位 <TABLE border=1> <THEAD> <TR> <TH>ID <TH>可用的过滤器 <TH>描述 <TBODY> <TR> <TD>FILTER_FLAG_STRIP_LOW <TD>FILTER_SANITIZE_ENCODED, FILTER_SANITIZE_SPECIAL_CHARS, FILTER_SANITIZE_STRING, FILTER_UNSAFE_RAW <TD>去除ASCII小于32的字符。 <TR> <TD>FILTER_FLAG_STRIP_HIGH <TD>FILTER_SANITIZE_ENCODED, FILTER_SANITIZE_SPECIAL_CHARS, FILTER_SANITIZE_STRING, FILTER_UNSAFE_RAW <TD>去除ASCII在于127的字符。 <TR> <TD>FILTER_FLAG_ALLOW_FRACTION <TD>FILTER_SANITIZE_NUMBER_FLOAT <TD>允许小数点分隔符(.) <TR> <TD>FILTER_FLAG_ALLOW_THOUSAND <TD>FILTER_SANITIZE_NUMBER_FLOAT, FILTER_VALIDATE_FLOAT <TD>允许千位分隔符(,) <TR> <TD>FILTER_FLAG_ALLOW_SCIENTIFIC <TD>FILTER_SANITIZE_NUMBER_FLOAT <TD>允许科学计数法(e或E)。 <TR> <TD>FILTER_FLAG_NO_ENCODE_QUOTES <TD>FILTER_SANITIZE_STRING <TD>不编码引号(单引号和双引号)。 <TR> <TD>FILTER_FLAG_ENCODE_LOW <TD>FILTER_SANITIZE_ENCODED, FILTER_SANITIZE_STRING, FILTER_SANITIZE_RAW <TD>编码ASCII小于32的字符。 <TR> <TD>FILTER_FLAG_ENCODE_HIGH <TD>FILTER_SANITIZE_ENCODED, FILTER_SANITIZE_SPECIAL_CHARS, FILTER_SANITIZE_STRING, FILTER_SANITIZE_RAW <TD>编码ASCII大于127的字母。 <TR> <TD>FILTER_FLAG_ENCODE_AMP <TD>FILTER_SANITIZE_STRING, FILTER_SANITIZE_RAW <TD>编码&符号。 <TR> <TD>FILTER_NULL_ON_FAILURE <TD>FILTER_VALIDATE_BOOLEAN <TD>返回null当验证数据不是以下字符串时(yes,no,1,0,true,false,on,off)。 <TR> <TD>FILTER_FLAG_ALLOW_OCTAL <TD>FILTER_VALIDATE_INT <TD>允许八进制数值(0开头)。 <TR> <TD>FILTER_FLAG_ALLOW_HEX <TD>FILTER_VALIDATE_INT <TD>允许16进制数值。(0X或是0x开头)。 <TR> <TD>FILTER_FLAG_IPV4 <TD>FILTER_VALIDATE_IP <TD>IP4格式字符串。 <TR> <TD>FILTER_FLAG_IPV6 <TD>FILTER_VALIDATE_IP <TD>IP6格式字符串。 <TR> <TD>FILTER_FLAG_NO_PRIV_RANGE <TD>FILTER_VALIDATE_IP <TD>RFC指定的私域IP。IP4如下范围10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16。或是IP6以下开头的域: FD或FC <TR> <TD>FILTER_FLAG_NO_RES_RANGE <TD>FILTER_VALIDATE_IP <TD>要求值不在保留的 IP 范围内。IPv4 ranges:0.0.0.0/8, 169.254.0.0/16,192.0.2.0/24 and 224.0.0.0/4。不能应用于IP6。 <TR> <TD>FILTER_FLAG_PATH_REQUIRED <TD>FILTER_VALIDATE_URL <TD>要求<ABBR title="Uniform Resource Locator">URL包含路径部分。 <TR> <TD>FILTER_FLAG_QUERY_REQUIRED <TD>FILTER_VALIDATE_URL <TD>要求<ABBR title="Uniform Resource Locator">URL查询字符串。 </script>
Statement
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
The Continued Use of PHP: Reasons for Its EnduranceThe Continued Use of PHP: Reasons for Its EnduranceApr 19, 2025 am 12:23 AM

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python: Exploring Their Similarities and DifferencesPHP and Python: Exploring Their Similarities and DifferencesApr 19, 2025 am 12:21 AM

PHP and Python are both high-level programming languages ​​that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP and Python: Different Paradigms ExplainedPHP and Python: Different Paradigms ExplainedApr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP and Python: A Deep Dive into Their HistoryPHP and Python: A Deep Dive into Their HistoryApr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Choosing Between PHP and Python: A GuideChoosing Between PHP and Python: A GuideApr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Frameworks: Modernizing the LanguagePHP and Frameworks: Modernizing the LanguageApr 18, 2025 am 12:14 AM

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHP's Impact: Web Development and BeyondPHP's Impact: Web Development and BeyondApr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

How does PHP type hinting work, including scalar types, return types, union types, and nullable types?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

See all articles

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

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software