search

Boolean验证 FILTER_VALIDATE_BOOLEAN

1 <?php2 3 /*** test for a boolean value ***/4 echo filter_var("true", FILTER_VALIDATE_BOOLEAN);5 //16 ?> 

上面的代码输出1,因为过滤器发现了一个有效的布尔值,下面列出了其它可以返回true的值
1
"1"
"yes"
"true"
"on"
TRUE
下列值将会返回false
0
"0"
"no"
"false"
"off"
""
NULL
FALSE
同时也支持下面的用法

1 <?php2 3 /*** a simple array ***/4 $array = array(1,2,3,4,5);5 6 /*** test for a boolean value ***/7 echo filter_var(in_array(3, $array), FILTER_VALIDATE_BOOLEAN) ? "TRUE" : "FALSE";8 //true9 ?>

 

在上面的代码中,先判断了in_array函数执行成功,返回了true,所以最后这段代码输出true
我们也可以传递一个数组,来判断数组中值的boolean类型

 1 <?php 2  3 /*** a multi dimensional array ***/ 4 $array = array(0,1,2,3,4, array(0,1,2,3,4)); 5  6 /*** create the list of values ***/ 7 $values = filter_var($array, FILTER_VALIDATE_BOOLEAN, FILTER_REQUIRE_ARRAY); 8  9 /*** dump the values ***/10 var_dump($values);11 12 ?>

 

上面代码输出如下:
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

 1 <?php 2  3 /*** an FLOAT value to check ***/ 4 $float = 22.42; 5  6 /*** validate with the FLOAT flag ***/ 7 if(filter_var($float, FILTER_VALIDATE_FLOAT) === false) 8 { 9     echo "$float is not valid!";10 }11 else12 {13     echo "$float is a valid floating point number";14 }15 ?> 

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

/*** 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) { }
}
浮点型过滤器支持我们指定一个数字间的分隔符

 1 <?php 2  3 /*** an array of floats with seperators ***/ 4 $floats = array( 5 "1,234" => ",", 6 "1.234" => "..", 7 "1.2e3" => "," 8 ); 9 10 /*** validate the floats against the user defined decimal seperators ***/11 foreach ($floats as $float => $dec_sep)12 {13     $out = filter_var($float, FILTER_VALIDATE_FLOAT,     array("options"=>array("decimal" => $dec_sep)));14     /*** dump the results ***/15     var_dump($out);16 }17 ?>

 

在上面的代码中,$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。

 1 <?php 2  3 /*** a rfc compliant web address ***/ 4 $url = "http://www.phpro.org"; 5  6 /*** try to validate the URL ***/ 7 if(filter_var($url, FILTER_VALIDATE_URL) === FALSE) 8 { 9     /*** if there is no match ***/10     echo "Sorry, $url is not valid!";11 }12 else13 {14     /*** if we match the pattern ***/15     echo "The URL, $url is valid!<br />";16 }17 ?>

 

上面的例子中通过简单的if语句来判断给定的URL是否合法,但并不是所有的URL都是这样的格式。有时候URL可是能是一个IP地址,也可能在URL中传递了多个参数。下面提供了几个flags来帮助我们验证URL
FILTER_FLAG_SCHEME_REQUIRED - 要求 URL 是 RFC 兼容 URL。(比如:http://example)
FILTER_FLAG_HOST_REQUIRED - 要求 URL 包含主机名(http://www.example.com)
FILTER_FLAG_PATH_REQUIRED - 要求 URL 在主机名后存在路径(比如:eg.com/example1/)
FILTER_FLAG_QUERY_REQUIRED - 要求 URL 存在查询字符串(比如:"eg.php?age=37")

 1 <?php 2  3 /*** a non rfc compliant URL ***/ 4 $url = "index.php"; 5  6 /*** try to validate the URL ***/ 7 if(filter_var($url, FILTER_VALIDATE_URL, FILTER_FLAG_SCHEME_REQUIRED) === FALSE) 8 { 9     /*** if there is no match ***/10    echo "Sorry, $url is not valid!";11 }12 else13 {14     /*** if the URL is valid ***/15     echo "The URL, $url is valid!";16 }17 ?>

 

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

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 过滤器把值作为电子邮件地址来验证。

 1 <?php 2 $email = "someone@exa mple.com"; 3  4 if(!filter_var($email, FILTER_VALIDATE_EMAIL)) 5  { 6      echo "E-mail is not valid"; 7  } 8 else 9  {10      echo "E-mail is valid";11  }12 ?>

自定义过滤器 FILTER_CALLBACK

FILTER_CALLBACK 过滤器使用用户自定义函数对值进行过滤。
这个过滤器为我们提供了对数据过滤的完全控制。
指定的函数必须存入名为 "options" 的关联数组中。

 1 <?php 2 function convertSpace($string) 3  { 4      return str_replace(" ", "_", $string); 5  } 6  7 $string = "Peter is a great guy!"; 8  9 echo filter_var($string, FILTER_CALLBACK,10 array("options"=>"convertSpace"));11 ?>

 

输出

Peter_is_a_great_guy!


PHP技术交流群 170855791

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