Php5.2 use the new input Filter Extension function [from IBM]

Source: Internet
Author: User

Receiving user input or any other data from untrusted sources is one of the most common risks that PHP developers may bear when developing applications. You often need to introduce data from unknown sources to run the application, but this gives hackers the opportunity to insert arbitrary code or use the application in other ways. From PHP v5.2 onwards, the input Filter Extension function will be enabled by default, so that you can more easily take measures for such operations. The input Filter Extension function provides a set of functions to parse and check input, and then use this input in the function.

We will examine the reasons for using these functions to parse and check input without manual encoding, and introduce some basic examples of how to use these new functions.

Input from any location

Input is critical to most applications. Our applications will receive a large amount of information and use the microprocessor capabilities to process it. We can control the position where the input enters the application, but we cannot control the intention of the user who inputs the data. PHP was initially developed as an easy way to develop scripts for collecting input from HTML forms. Its functions are no longer limited, but we are still using it to collect and operate data from many untrusted sources. Even a single data input employee may unconsciously send some problematic data to the application, and even must regard it as an untrusted source.

Security is currently a very popular issue, and has become more popular with each hardware and software revision. We always speak well, but because the situation is complicated, we often do poorly on the key point of system protection-input. There are many methods and the implementation is complicated. We have a strict deadline for completing the application and must fulfill the deadline of the Project Manager.

One way to protect yourself from malicious code attacks is to ensure that the expected input is received. In this article, we will look at an example that prevents users from entering inappropriate JavaScript, and show you how to strip the markup from the input and return the actual content.

PHP V5.0 and later versions provide the input Filter Extension Feature to make it easier for you to obtain security. PHP v5.2 is enabled by default for the first time and is out-of-the-box.

 

Comparison between verification and filtering

You may have heard of the terms in your programming experience:Input verification. It is a vital part of the application development process. It is used to ensure that incoming data is correct in context and content. Programmers can use regular expressions and tests to check whether the value meets the standard (for example, when an email address is required and the input format is correct ). You can also use this method to exclude free email addresses such as Hotmail or gmail. You will use a regular expression to block any email addresses that contain "hotmail.com" or "gmail.com.

This type of "processing basic checks to ensure that input data meets certain criteria" is usually considered to be verification. In this case, make sure that you do not have to clear the data or obtain the searched data. The purpose of verification is to avoid some simple errors, such as trying to put null into a field that does not accept this value.

Errors Caused by wrong data or maliciously constructed data may have devastating consequences. You will need to fully implement a more comprehensive method to filter this information, which should cover all possible tests for each data type, rather than performing the same or repeated tasks. Generally, you may not notice testing or writing incomplete regular expressions. The Filter Extension function will help provide more complete input evaluation and reduce repeated code writing. In this case, the difference between filtering and verification is that filtering is more comprehensive in terms of security.

 

 

Filter Type and how to select

Let's further view the details of the extended functions. The Filter Extension function has two filters: sanitizing and logical.

The sanitizing filter only allows or disables characters in a string and returns the cleansed string as a result. No matter which data format you pass in these functions, they always return strings. This is critical for the use of specific types, because you can prevent users from sending inappropriate input and causing abnormal results. For example, you can find that the text block input is returned to the following page and the returned information is used. If the input is cleared, all dangerous parts of the input are deleted.

The logical filter tests the variables and provides true or false results based on the tests. Then you can use the results to determine how to process data or obtain the user's address. A simple example of this filter is to verify the age. The logic test can also be performed on regular expressions similar to Perl.

Let's take a look at some methods to use these functions for filtering and verification, and learn how to introduce filtering into the application.

 

Organize Behaviors

Let's begin to use the Filter Extension function to clean up applications to filter unwanted code blocks.

In this example application, you have a simple form that receives three questions and three answers. The form itself does not use verification or filtering. When viewing the source code, an unfortunate user believes this is true and decides to test the form by writing text blocks that contain JavaScript calls that throw an alarm. If an alert pops up, it indicates that all input content will be accepted and used by the application without being filtered. This proves that it is correct.

List 1. Simple input form

                

Listing 1 is a common HTML form that accepts user input. The user is required to provide basic information and simply return it without any other operations. In Figure 1, you can see that the user has entered some information and is ready to send JavaScript code. If the cleaning is not completed, this JavaScript code will send an alarm.

Figure 1. Input Form
 

Next, create a script to capture the form variables and print them out on another page.

List 2. PHP form

                <body> <?php  echo "You are " . $_GET['1'] . ".<br>/n"; echo "Your favorite color is " . $_GET['2'] . ".<br>/n"; echo "The airspeed of an unladen swallow is " . $_GET['3'] . ".<br>/n"; ?></body>

Now you can see what will happen if you only return this input without any type of filtering.

Figure 2. Form output
 

As you can see, unfortunately users have executed some random code. Assume that this code is only on the client (unfortunately, the user's PC is included, and in this case it does not represent a threat to the application), but it is definitely not a valid input.

 

 

Clear input string

Listing 3 demonstrates how to usefilter_var()OfFILTER_SANITIZE_STRINGSimple example.

Listing 3. Add code to receive a PHP script

                 <?php  echo "You are " . filter_var($_GET['1'], FILTER_SANITIZE_STRING) . ".<br>/n"; echo "Your favorite color is " . filter_var($_GET['2'], FILTER_SANITIZE_STRING) . ".<br>/n"; echo "The airspeed of an unladen swallow is "    . filter_var($_GET['3'], FILTER_SANITIZE_STRING) . ".<br>/n"; ?>

As you can see, start to usefilter_var()Function to clear the input and make it valid and secure. In this case, useFILTER_SANITIZE_STRINGThis option will get the input, delete all HTML tags, and selectively encode or delete specific characters.

Because it will remove the HTML Tag, trying to run javascript will fail and get more appropriate results from the script.

Figure 3. Cleaned output from the revised PHP script
 

You can usefilter_var()Functions greatly reduce the amount of encoding. In that case, you will have to write several additional lines of code and explicit regular expressions that only execute the HTML code block, and parse the text block of the entire input to ensure that no HTML Tag is missing. Using the provided functions will be simpler.

 

 

User input-no logic

Some inputs are numbers or have a specified style. In these cases, you can use the logical filter option and check data for expressions or other logical tests. If the expression reads true, the data is successfully filtered. If the logic test proves that the data is false, the data cannot pass the filter. First, we will set up a simple logic test to check that the swallow's fall speed is within the specified range, because the swallow's air speed may be different. After the test is set, we will add some code to tell the user whether the answer is correct. The correct answer should be repeated.

Listing 4. Add code to receive PHP scripts

                <?php  echo "You are " . $_GET['1'] . ".<br>/n"; echo "Your favorite color is " . $_GET['2'] . "./n/n";$minSpeed = 12;$maxSpeed = 13;$airspeed = filter_var($_GET['3'], FILTER_VALIDATE_INT, array("options" => array("min_range"=>$minSpeed, "max_range"=>$maxSpeed))); echo "The airspeed of an unladen swallow is " . $airspeed . "./n/n"; ?>

Listing 4 checks the answer to the falling swallow question based on the minimum and maximum speed ranges. This ensures that it is indeedINTVariable, but also$minSpeedAnd$maxSpeed. If the user's answer is not within the acceptable value range, the result will beFALSE. Then you can test the answer and return the correct answer to the user. In this case, we will be outspoken.

Listing 5. Add code to receive PHP scripts

                <?php  echo "You are " . $_GET['1'] . ".<br>/n"; echo "Your favorite color is " . $_GET['2'] . "./n/n";$minSpeed = 12;$maxSpeed = 13;$airspeed = filter_var($_GET['3'], FILTER_VALIDATE_INT, array("options" => array("min_range"=>$minSpeed, "max_range"=>$maxSpeed)));If ($airspeed === FALSE){Echo " echo "The airspeed of an unladen swallow is " . $airspeed . "./n/n";} ?>

We have successfully tested the incoming data in compliance with the logic test and displayed the correct results or some negative feedback to the user. In any case, we have used a filter to ensure that the correct answer is provided for the input.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.