Php Data filtering function and method example, php filter function example

Source: Internet
Author: User
Tags php form

Php Data filtering function and method example, php filter function example
1. Basic principles of php Data submission and filtering

1) when submitting variables to the database, we must use addslashes () for filtering. For example, we can solve an addslashes () problem. In fact, when variable values are involved, the intval () function is also a good choice for string filtering.

2) Enable magic_quotes_gpc and magic_quotes_runtime in php. ini. Magic_quotes_gpc can change the quotation marks in get, post, and cookie to a slash. Magic_quotes_runtime can be used as a format for inbound and outbound data. In fact, this parameter is very popular as early as the previous injection was crazy.

3) when using system functions, you must use the escapeshellarg () and escapeshellcmd () parameters to filter them out, so that you can safely use the system functions.

4) for Cross-Site, strip_tags () and htmlspecialchars () parameters are both good, and user-submitted tags with html and php will be converted. For example, the angle brackets "<" are converted to harmless characters such as "<.

The Code is as follows:

$ New = htmlspecialchars ("Test", ENT_QUOTES );

Strip_tags ($ text ,);

5) filter related functions, such as the previous include (), unlink, and fopen () functions. As long as you specify the variables for the operation you want to perform or strictly filter the relevant characters, I think this will be impeccable.

2. Simple PHP Data Filtering

1) warehouse receiving: trim ($ str), addslashes ($ str)

2) outbound: stripslashes ($ str)

3) display: htmlspecialchars (nl2br ($ str ))

Take the following example to further discuss the dispatch. php script:

The Code is as follows:

/* Global Security Processing */switch ($ _ GET ['task']) {case 'print _ form': include '/inc/presentation/form. inc '; break; case 'process _ form': $ form_valid = false; include'/inc/logic/process. inc '; if ($ form_valid) {include'/inc/presentation/end. inc ';} else {include'/inc/presentation/form. inc ';} break; default: include'/inc/presentation/index. inc '; break;}?>

  



If this is the only publicly accessible PHP script, it is certain that the design of this program ensures that the global security processing cannot be bypassed at the beginning. At the same time, developers can easily see the control process of specific tasks. For example, you do not need to browse the entire code to easily know: When $ form_valid is true, end. inc is unique to the user; because it is in process. before inc is included, it is initialized to false. It can be determined that process. inc's internal logic sets it to true; otherwise, the form is displayed again (related error messages may be displayed ).

Note:

If you use directory-oriented files such as index. php (instead of dispatch. php), you can use URL address: 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.

Inclusion Method

Another way is to use a separate module, which is responsible for all security processing. This module is included in the front-end (or very front-end) of all open PHP scripts ). Refer to the following Script security. inc.

The Code is as follows:

  
switch ($_POST['form'])  {  case 'login':  $allowed = array();  $allowed[] = 'form';  $allowed[] = 'username';  $allowed[] = 'password';  $sent = array_keys($_POST);  if ($allowed == $sent)  {  include '/inc/logic/process.inc';  }  break;  }  ?>

  


In this example, each submitted form is considered to contain the unique verification value of form, and security. inc independently processes the data to be filtered by 0 in the form. The HTML form to implement this requirement is as follows:

The Code is as follows:

Username:

Password:

The $ allowed array is used to check which form variable is allowed. This list should be consistent before the form is processed. Process control determines what to execute, and process. inc is the place where the filtered data arrives.

Note:

To ensure that security. inc is always included in the beginning of each script, use auto_prepend_file.

Example of Filtering

Creating a whitelist is very important for data filtering. Since it is impossible to give an example of every possible form data, some examples can help you have a general understanding of this.

The following code verifies the email address:

The Code is as follows:

  
$clean = array();  $email_pattern = '/^[^@s<&>]+@([-a-z0-9]+.)+[a-z]{2,}$/i';  if (preg_match($email_pattern, $_POST['email'])) {  $clean['email'] = $_POST['email'];  }  ?>

  



The following code ensures that the content of $ _ POST ['color'] is red, green, or blue:

The Code is as follows:

 
 $clean = array();  switch ($_POST['color']) {  case 'red':  case 'green':  case 'blue':  $clean['color'] = $_POST['color'];  break;  }  ?>

  



The following code ensures that $ _ POST ['num'] is an integer ):

The Code is as follows:

  
         $clean = array();  if ($_POST['num'] == strval(intval($_POST['num']))) {  $clean['num'] = $_POST['num'];  }

  



The following code ensures that $ _ POST ['num'] is a floating point number (float ):

The Code is as follows:

  
$clean = array();  if ($_POST['num'] == strval(floatval($_POST['num'])))  {  $clean['num'] = $_POST['num'];  }

  



?>

Name Conversion

In the previous example, an array $ clean is used. It is a good habit for developers to determine whether data has potential threats. Never save the data in $ _ POST or $ _ GET after verification. As a developer, you should always be skeptical about the data stored in the super global array.

It should be added that using $ clean can help you think about what else is not filtered, which is more like a whitelist. This improves the security level.

If you only save the verified data to $ clean, the only risk in data verification is that the referenced array element does not exist, rather than the unfiltered hazardous data.

Timing

Once the PHP script starts to be executed, it means that all HTTP requests have ended. In this case, the user has no chance to send data to the script. Therefore, no data can be input to the script (even when register_globals is enabled ). This is why initialization of variables is a good habit.

Anti-Injection

  
The Code is as follows: copy the code // PHP full site anti-injection program. You Need To require_once in the public file. // determine the magic_quotes_gpc status if (@ get_magic_quotes_gpc ()) {$ _ GET = sec ($ _ GET); $ _ POST = sec ($ _ POST); $ _ COOKIE = sec ($ _ COOKIE ); $ _ FILES = sec ($ _ FILES);} $ _ SERVER = sec ($ _ SERVER); function sec (& $ array) {// if it is an array, traverse the array, recursively call if (is_array ($ array) {foreach ($ array as $ k = >$ v) {$ array [$ k] = sec ($ v );}} else if (is_string ($ array )){ // Use the addslashes function to process $ array = addslashes ($ array);} else if (is_numeric ($ array) {$ array = intval ($ array );} return $ array;} // integer filter function num_check ($ id) {if (! $ Id) {die ('parameter cannot be blank! ');} // Determines whether else if (inject_check ($ id) {die ('invalid parameter');} // determines whether else if (! Is_numetic ($ id) {die ('invalid parameter');} // number judgment $ id = intval ($ id); // integer return $ id ;} // function str_check ($ str) {if (inject_check ($ str) {die ('invalid parameter ');} // inject $ str = htmlspecialchars ($ str); // convert html return $ str;} function search_check ($ str) {$ str = str_replace ("_", "_", $ str); // filter out "_" $ str = str_replace ("%", "%", $ str ); // filter out "%" $ str = htmlspecialchars ($ str );/ /Convert html return $ str;} // form filter function post_check ($ str, $ min, $ max) {if (isset ($ min) & strlen ($ str) <$ min) {die ('minimum $ min byte ');} else if (isset ($ max) & strlen ($ str)> $ max) {die ('maximum $ max byte ');} return stripslashes_array ($ str);} // anti-injection function inject_check ($ SQL _str) {return eregi ('select | inert | update | delete | '|/* | .. /|. /| UNION | into | load_file | outfile ', $ SQL _str ); // Row filtering, anti-injection} function stripslashes_array (& $ array) {if (is_array ($ array) {foreach ($ array as $ k => $ v) {$ array [$ k] = stripslashes_array ($ v) ;}} else if (is_string ($ array) {$ array = stripslashes ($ array );} return $ array ;}?>

  



 


Php form filtering process for retrieving user input data

Addslashes
Htmlspecialchars

Mysql_real_escape_string
Intval () can be used for numbers. It is best to loop $ _ POST, one by one addslashes or other functions before.
All of the above can be done as needed.

Data Filtering in php

Assume that your data is in the Data $ demo. We will write a code segment for filtering.
$ Count = 0;
Foreach ($ demo as $ ditem ){
If ($ ditem ['a'] = 0) | ($ ditem ['B'] = 0) | ($ ditem ['C'] = 0) | ($ ditem ['C'] = 0) continue;
Echo $ ditem ['id']. ''. $ ditem ['a']. ''. $ ditem ['B']. ''. $ ditem ['C']. ''. $ ditem ['D']. ''. $ ditem ['E']. "<br> ";
$ Count ++;

}
Echo 'Total number of rows: '. $ count;

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.