search
HomeBackend DevelopmentPHP TutorialComprehensive analysis of PHP Filter filter_php example

PHP filters are used to validate and filter data from non-secure sources, such as user input.

What are PHP filters?

PHP filters are used to validate and filter data from non-secure sources.

Validating and filtering user input or custom data is an important part of any web application.

Filter extensions for PHP are designed to make data filtering easier and faster.

Why use filters?

Almost all web applications rely on external input. This data usually comes from users or other applications (such as web services). By using filters, you can ensure that your application gets the correct input type.

You should always filter external data!

Input filtering is one of the most important application security topics.

What is external data?

•Input data from forms

•Cookies

•Server variables

•Database query results

Functions and Filters

To filter variables, use one of the filter functions below:

•filter_var() - Filter a single variable by a specified filter

•filter_var_array() - Filter multiple variables with the same or different filters

•filter_input - Get an input variable and filter it

•filter_input_array - take multiple input variables and filter them through the same or different filters

In the example below, we validate an integer using the filter_var() function:

<&#63;php
$int = 123;
if(!filter_var($int, FILTER_VALIDATE_INT))
{
echo("Integer is not valid");
}
else
{
echo("Integer is valid");
}
&#63;> 

The above code uses the "FILTER_VALIDATE_INT" filter to filter variables. Since this integer is legal, the output of the code is: "Integer is valid".

If we try to use a non-integer variable, the output is: "Integer is not valid".

For a complete list of functions and filters, visit our PHP Filter Reference Manual.

Validating and Sanitizing

There are two types of filters:

Validating filter:

•Used to validate user input

•Strict formatting rules (such as URL or Email validation)

•Returns the expected type if successful, or FALSE if failed

Sanitizing filter:

•Used to allow or prohibit specified characters in a string

•No data format rules

•Always returns a string

Options and Flags

Options and flags are used to add additional filtering options to the specified filter.

Different filters have different options and flags.

In the example below, we validate an integer using filter_var() with the "min_range" and "max_range" options:

<&#63;php
$var=300;
$int_options = array(
"options"=>array
(
"min_range"=>0,
"max_range"=>256
)
);
if(!filter_var($var, FILTER_VALIDATE_INT, $int_options))
{
echo("Integer is not valid");
}
else
{
echo("Integer is valid");
}
&#63;> 

Just like the code above, the options must be put into a related array called "options". If using flags, they don't need to be in an array.

Since the integer is "300", which is not within the specified range, the output of the above code will be "Integer is not valid".

For a complete list of functions and filters, please visit the PHP Filter Reference Manual provided by W3School. You can see the available options and flags for each filter.

Validate input

Let's try to validate the input from the form.

The first thing we need to do is confirm that the input data we are looking for exists.

Then we use the filter_input() function to filter the input data.

In the example below, the input variable "email" is passed to the PHP page:

<&#63;php
if(!filter_has_var(INPUT_GET, "email"))
{
echo("Input type does not exist");
}
else
{
if (!filter_input(INPUT_GET, "email", FILTER_VALIDATE_EMAIL))
{
echo "E-Mail is not valid";
}
else
{
echo "E-Mail is valid";
}
}
&#63;>

Example explanation:

The example above has an input variable (email) passed via the "GET" method:

1. Detect whether there is an "email" input variable of "GET" type

2. If there is an input variable, check whether it is a valid email address

Purify input

Let’s try to clean up the URL passed from the form.

First, we want to confirm that the input data we are looking for exists.

Then, we use the filter_input() function to purify the input data.

In the example below, the input variable "url" is passed to the PHP page:

<&#63;php
if(!filter_has_var(INPUT_POST, "url"))
{
echo("Input type does not exist");
}
else
{
$url = filter_input(INPUT_POST, "url", FILTER_SANITIZE_URL);
}
&#63;> 

例子解释:

上面的例子有一个通过 "POST" 方法传送的输入变量 (url):

1.检测是否存在 "POST" 类型的 "url" 输入变量

2.如果存在此输入变量,对其进行净化(删除非法字符),并将其存储在 $url 变量中

假如输入变量类似这样:"http://www.W3非o法ol.com.c字符n/",则净化后的 $url 变量应该是这样的:
http://www.W3School.com.cn/

过滤多个输入

表单通常由多个输入字段组成。为了避免对 filter_var 或 filter_input 重复调用,我们可以使用 filter_var_array 或 the filter_input_array 函数。

在本例中,我们使用 filter_input_array() 函数来过滤三个 GET 变量。接收到的 GET 变量是一个名字、一个年龄以及一个邮件地址:

<&#63;php
$filters = array
(
"name" => array
(
"filter"=>FILTER_SANITIZE_STRING
),
"age" => array
(
"filter"=>FILTER_VALIDATE_INT,
"options"=>array
(
"min_range"=>1,
"max_range"=>120
)
),
"email"=> FILTER_VALIDATE_EMAIL,
);
$result = filter_input_array(INPUT_GET, $filters);(array(3) { ["name"]=> string(1) "1" ["age"]=> bool(false) ["email"]=> string(8) "1@qq.com" })
if (!$result["age"])
{
echo("Age must be a number between 1 and 120.<br />");
}
elseif(!$result["email"])
{
echo("E-Mail is not valid.<br />");
}
else
{
echo("User input is valid");
}
&#63;> 

例子解释:

上面的例子有三个通过 "GET" 方法传送的输入变量 (name, age and email)

1.设置一个数组,其中包含了输入变量的名称,以及用于指定的输入变量的过滤器

2.调用 filter_input_array 函数,参数包括 GET 输入变量及刚才设置的数组

3.检测 $result 变量中的 "age" 和 "email" 变量是否有非法的输入。(如果存在非法输入,)

filter_input_array() 函数的第二个参数可以是数组或单一过滤器的 ID。

如果该参数是单一过滤器的 ID,那么这个指定的过滤器会过滤输入数组中所有的值。

如果该参数是一个数组,那么此数组必须遵循下面的规则:

•必须是一个关联数组,其中包含的输入变量是数组的键(比如 "age" 输入变量)

•此数组的值必须是过滤器的 ID ,或者是规定了过滤器、标志以及选项的数组

使用 Filter Callback

通过使用 FILTER_CALLBACK 过滤器,可以调用自定义的函数,把它作为一个过滤器来使用。这样,我们就拥有了数据过滤的完全控制权。

您可以创建自己的自定义函数,也可以使用已有的 PHP 函数。

规定您准备用到过滤器函数的方法,与规定选项的方法相同。

在下面的例子中,我们使用了一个自定义的函数把所有 "_" 转换为空格:

<&#63;php
function convertSpace($string)
{
return str_replace("_", " ", $string);
}
$string = "Peter_is_a_great_guy!";
echo filter_var($string, FILTER_CALLBACK, array("options"=>"convertSpace"));
&#63;> 

以上代码的结果是这样的:

Peter is a great guy!

例子解释:

上面的例子把所有 "_" 转换成空格:

1.创建一个把 "_" 替换为空格的函数

2.调用 filter_var() 函数,它的参数是 FILTER_CALLBACK 过滤器以及包含我们的函数的数组

以上所述是小编给大家介绍的PHP Filter过滤器全面解析,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对脚本之家网站的支持!

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
How do you set the session cookie parameters in PHP?How do you set the session cookie parameters in PHP?Apr 22, 2025 pm 05:33 PM

Setting session cookie parameters in PHP can be achieved through the session_set_cookie_params() function. 1) Use this function to set parameters, such as expiration time, path, domain name, security flag, etc.; 2) Call session_start() to make the parameters take effect; 3) Dynamically adjust parameters according to needs, such as user login status; 4) Pay attention to setting secure and httponly flags to improve security.

What is the main purpose of using sessions in PHP?What is the main purpose of using sessions in PHP?Apr 22, 2025 pm 05:25 PM

The main purpose of using sessions in PHP is to maintain the status of the user between different pages. 1) The session is started through the session_start() function, creating a unique session ID and storing it in the user cookie. 2) Session data is saved on the server, allowing data to be passed between different requests, such as login status and shopping cart content.

How can you share sessions across subdomains?How can you share sessions across subdomains?Apr 22, 2025 pm 05:21 PM

How to share a session between subdomains? Implemented by setting session cookies for common domain names. 1. Set the domain of the session cookie to .example.com on the server side. 2. Choose the appropriate session storage method, such as memory, database or distributed cache. 3. Pass the session ID through cookies, and the server retrieves and updates the session data based on the ID.

How does using HTTPS affect session security?How does using HTTPS affect session security?Apr 22, 2025 pm 05:13 PM

HTTPS significantly improves the security of sessions by encrypting data transmission, preventing man-in-the-middle attacks and providing authentication. 1) Encrypted data transmission: HTTPS uses SSL/TLS protocol to encrypt data to ensure that the data is not stolen or tampered during transmission. 2) Prevent man-in-the-middle attacks: Through the SSL/TLS handshake process, the client verifies the server certificate to ensure the connection legitimacy. 3) Provide authentication: HTTPS ensures that the connection is a legitimate server and protects data integrity and confidentiality.

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.

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

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools