PHP Data filtering function _ PHP Tutorial

Source: Internet
Author: User
PHP Data filtering function. 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 () injection problem. 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:

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:

// PHP full-site anti-injection program, which must be included in the public file require_once
// 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 and call it recursively
If (is_array ($ array )){
Foreach ($ array as $ k => $ v ){
$ Array [$ k] = sec ($ v );
}
} Else if (is_string ($ array )){
// Use the addslashes function for processing
$ Array = addslashes ($ array );
} Else if (is_numeric ($ array )){
$ Array = intval ($ array );
}
Return $ array;
}
// Integer filter function
Function num_check ($ id ){
If (! $ Id ){
Die ('parameter cannot be blank! ');
} // Whether it is null
Else if (inject_check ($ id )){
Die ('invalid parameter ');
} // Injection judgment
Else if (! Is_numetic ($ id )){
Die ('invalid parameter ');
}
// Digital judgment
$ Id = intval ($ id );
// Integer
Return $ id;
}
// Character filtering function
Function str_check ($ str ){
If (inject_check ($ str )){
Die ('invalid parameter ');
}
// Injection judgment
$ 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
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
Function inject_check ($ SQL _str ){
Return eregi ('select | inert | update | delete | '|/* |.../|./| UNION | into | load_file | outfile', $ SQL _str );
// Www.111cn.net for filtering and 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;
}
?>

When submitting a variable to the database, we must use addslashes () for filtering. for example, we can solve an addslashes () problem. Its...

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.