Explore the safe way of PHP data filtering _php Tutorial

Source: Internet
Author: User
InAt the beginning of the guide, we said that data filtering is the cornerstone of Web application security in any language, on any platform. This includes checking the data entered into the app and outputting the data from the app, and a good software design can help developers:

Ensure that PHP data filtering cannot be bypassed, that illegal information is not affected by legitimate information, and that the source of the data is identified.

There are a variety of viewpoints on how to ensure that data filtering cannot be bypassed, and two of them are more generic and provide a higher level of protection than others.

PHP Data Filtering scheduling method

This method is dispatched with a single PHP script (via URL). Any other action is included when necessary by using include or require. This approach typically requires that each URL be passed a separate get variable for dispatch. This get variable can be thought of as a more streamlined design for replacing script names. For example:

Http://example.org/dispatch.php?task=print_formdispatch.php is the only root file (document root). It allows developers to do two things that are very important:

At the beginning of dispatch.php, some global security processing is implemented, and it is ensured that these processes cannot be bypassed. It is easy to make sure that data is filtered where necessary, especially for special purpose control flow operations. Take a look at the following example to further discuss the dispatch.php script:

 
  
  
  1. < PHP
  2. /* Global security handling */
  3. switch ($_get[' task ') {case
    ' Print_form ': include '/inc/
    Presentation/form.inc ';
  4. break;
  5. case ' Process_form ': $ form_valid = /span>false ;
  6. include '/inc/logic/process.inc ';
  7. if ($form _valid) {include '/inc/
    Presentation/end.inc ';} Else{include
    '/inc/presentation/form.inc ';}
    Break;default:include '/inc/presentation
    /index.inc ';
  8. break;
  9. }
  10. ?>

If this is the only publicly accessible PHP script, you can be sure that the program is designed to ensure that the initial global security processing cannot be bypassed. It also makes it easy for developers to see the flow of control for specific tasks. For example, it is easy to know that you do not need to browse the entire code: When $form_valid is true, End.inc is the only one that is displayed to the user, because it is initialized to False before Process.inc is included, it can be determined that the internal logic of PROCESS.INC will set it to true, otherwise the form will be displayed again (possibly with related error messages).

PHP Data filtering issues to be aware of

If you use directory-directed files, such as index.php (instead of dispatch.php), you can use URL addresses like this: Http://example.org/?task=print_form.

You can also use Apacheforcetype redirection or mod_rewrite to adjust the URL address: Http://example.org/app/print-form.

How to include PHP data filtering

Another way is to use a single module, which is responsible for all the security processing. This module is included in the front (or very top) of all public PHP scripts. Refer to the following script Security.inc

 
 
    1. < ? php
    2. Switch ($_post[' form ')
    3. {case ' login ':
    4. $ allowed = array ();
    5. $allowed [] = ' form ';
    6. $allowed [] = ' username ';
    7. $allowed [] = ' password ';
    8. $ sent = Array_keys ($_post);
    9. if ($ allowed = = $sent)
    10. li> {include '/inc/logic/
      Process.inc ';}
    11. break;
    12. }
    13. ?>

In this PHP data filter example, each submitted form considers that it should contain the unique validation value of form, and security.inc independently processes 0 of the data that needs to be filtered in the form. The HTML form that implements this requirement is as follows:

 
 
  1. < form. action="/receive.php"
    Method = "POST" >
  2. < input type="hidden"
    name = "Form" value="Login" />
  3. < p>Username:
  4. < input type="text" name="username" />
  5. < / P >
  6. < p>Password:<input
    type = "Password" name="password" />
  7. < / P >
  8. < input type="Submit" />
  9. < /form >

An array called $allowed is used to verify which form variables are allowed, and this list should be consistent before the form is processed. Process Control determines what to do, and Process.inc is where the real filtered data arrives.

Attention

A good way to make sure that Security.inc is always included in the first place of each script is to use the Auto_prepend_file setting.

Examples of PHP data filtering

Creating a whitelist is very important for PHP data filtering. Because it is not possible to give an example of each of the form data that you might encounter, some examples can help you get a general idea of this.

The following code validates the e-mail address:

 
  
  
  1. < ? PHP
  2. $ Clean Array();
  3. $ Email_pattern '
    /^[^@s<&>]+@ ([-a-z0-9]+.)
    +[a-z]{2,}$/i ';
  4. if (Preg_match ($email _
    pattern, $_post[' email '))
  5. {$clean [' email '] = $_post
    [' Email '];}
  6. ?>

The following PHP Data filter code ensures that the content of $_post[' color ' is Red,green, or blue:

 
  
  
  1. < ? PHP
  2. $ Clean Array();
  3. Switch ($_post[' color ')


    $_post[' Color '];
  4. Break
  5. }
  6. ?>

The following PHP Data filter code ensures that $_post[' num ' is an integer:

 
  
  
  1. < ? PHP
  2. $ Clean Array();

  3. Strval (Intval ($_
    post[' num '])) {$clean
    [' num '] = $_post[' num '];
  4. }
  5. ?>

The following PHP Data filter code ensures that $_post[' num ' is a floating-point number (float):

 
  
  
  1. < ? PHP
  2. $ Clean Array();

  3. Strval (Floatval ($_post

    = $_post[' num '];
  4. }
  5. ?>

PHP Data filtering for name conversion

Each of the previous examples used array $clean. This is a good habit for developers to judge whether data is potentially a threat. Never save it in $_post or $_get after validating the data, as developers should always be fully skeptical of the data stored in the Super Global array.

What needs to be added is that the use of $clean can help to think about what else is not being filtered, which is more like a whitelist role. The level of security can be increased.

If you only save the validated data in $clean, the only risk to data validation is that the array element you are referencing does not exist, not the unfiltered hazard data.

The timing of PHP data filtering

Once the PHP script starts executing, it means that the HTTP request is all over. At this point, the user has no chance to send data to the script. Therefore, no data can be entered into the script (even if the register_globals is turned on). That's why initializing variables is a very good habit.


http://www.bkjia.com/PHPjc/446197.html www.bkjia.com true http://www.bkjia.com/PHPjc/446197.html techarticle at the beginning of the guide, we said that data filtering is the cornerstone of Web application security in any language, on any platform. This includes checking the data entered into the app and outputting the data from the app ...

  • 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.