Examples of PHP data filtering functions and methods

Source: Internet
Author: User
Tags html form http request php script strlen

1, the basic principles of data filtering of PHP submission

1 Submit variables into the database, we must use Addslashes () to filter, like our injection problem, a addslashes () is done. In fact, when it comes to variable values, the Intval () function is a good choice for string filtering.

2) Open MAGIC_QUOTES_GPC and Magic_quotes_runtime in php.ini. MAGIC_QUOTES_GPC can turn the quotes in the Get,post,cookie into slashes. Magic_quotes_runtime data that goes in and out of a database can play a role in formatting. In fact, this parameter is very popular as long ago when the injection was crazy.

3 When using System functions, you must use Escapeshellarg (), escapeshellcmd () parameters to filter, so you can rest assured that the use of system functions.

4 for the Cross Station, Strip_tags (), Htmlspecialchars () Two parameters are good, for the user submitted with HTML and PHP tags will be converted. For example, the angle bracket "<" will be converted to "<" such harmless characters.

The code is as follows Copy Code
$new = Htmlspecialchars ("<a href= ' test ' >Test</a>", ent_quotes);
Strip_tags ($text,);

5 for the correlation function filtering, just like the previous include (), Unlink,fopen (), and so on, as long as you have to perform the operation of the variable specified or the relevant characters filter tight, I think this is perfect.

2, PHP simple data filtering

1) Warehousing: Trim ($STR), Addslashes ($STR)
2) out of the library: stripslashes ($STR)
3) Display: Htmlspecialchars (NL2BR ($STR))


look at the following example to further discuss the dispatch.php script:

  code is as follows copy code

<?php

/* 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 program is designed to ensure that the first global security processing cannot be bypassed. It also makes it easy for developers to see the control process for specific tasks. For example, it's easy to know that when $form_valid is true, you don't need to browse the entire code: End.inc is the only one that is displayed to the user, and because it is only initialized to False before Process.inc is included, it is possible to determine that the internal logic of PROCESS.INC will set it to true; otherwise the form will appear again (possibly with related error messages).
Note
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.
include method
Another way is to use a separate module, which is responsible for all security processing. This module is included in the front end of all publicly available PHP scripts (or the very front part). Refer to the following script Security.inc

The code is as follows Copy Code

<?php

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 case, 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 shown below:

  code is as follows copy code
<form action= "/receive.php" method= "POST"
<input type= "hidden" name= "form" value= "login"/>
<p> Username:
<input type= "text" name= "Username"/></P>
<p>password:
<input type= " Password "name=" password/></p>
<input type= "Submit"/>
</form>

An array called $allowed is used to verify which form variables are allowed, and the list should be consistent before the form is processed. Process Control determines what to do, and Process.inc is where the data is actually filtered.
Attention
It is better to make sure that Security.inc is always included in the first position of each script by using the Auto_prepend_file setting.
Examples of filtering
The establishment of whitelist is very important for data filtering. Because it is not possible to give examples of each form data that may be encountered, some examples can help you to have a general understanding of this.
The following code verifies the e-mail address:

The code is as follows Copy Code

<?php

$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 contents of $_post[' color ' are red,green, or blue:

The code is as follows Copy Code

<?php

$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 (integer):

The code is as follows Copy Code

<?php

$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 Copy Code

<?php

$clean = Array ();

if ($_post[' num '] = = Strval (floatval ($_post[' num ')))
{
$clean [' num '] = $_post[' num '];
}

?>


Name Conversion
Each of the previous examples uses an array $clean. This is a good habit for developers to determine whether the data has a potential threat. Never, after validating data, keep it in $_post or $_get, as developers should always remain fully skeptical of data stored in the Super Global array.
To add, the use of $clean can help to think about what's not being filtered, which is more like a whitelist role. Can raise the level of security.
If only the validated data is stored in $clean, the only risk to data validation is that the array element you are referencing does not exist, rather than the unfiltered risk data.
Time
Once the PHP script starts executing, it means that the HTTP request has all ended. At this point, the user will not have the opportunity to send data to the script. Therefore, no data can be entered into the script (even if the register_globals is opened). That's why initializing variables is a very good habit.


Anti-injection

The code is as follows Copy Code

? Php
PHP Whole station Anti-injection program, need to require_once the document in the public file
Judge the state of MAGIC_QUOTES_GPC
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's an array, iterate through the array, recursively call the
if (Is_array ($array)) {
foreach ($array as $k => $v) {
$array [$k] = sec ($v);
}
else if (is_string ($array)) {
Use the Addslashes function to handle
$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 empty! ' );
}//IS NULL judgment
else if (Inject_check ($id)) {
Die (' illegal parameters ');
}//Injection judgment
else if (! is_numetic ($id)) {
Die (' illegal parameters ');
}
Digital judgment
$id = Intval ($id);
Integral type
return $id;
}
Character Filter function
function Str_check ($STR) {
if (Inject_check ($STR)) {
Die (' illegal parameters ');
}
Injection judgment
$str = Htmlspecialchars ($STR);
Convert HTML
return $str;
}
function Search_check ($STR) {
$str = Str_replace ("_", "_", $str);
To filter Out "_"
$str = str_replace ("%", "%", $str);
Filter out "%"
$str = Htmlspecialchars ($STR);
Convert HTML
return $str;
}
Form Filter Functions
function Post_check ($str, $min, $max) {
if (Isset ($min) && strlen ($STR) < $min) {
Die (' least $min byte ');
else if (isset ($max) && strlen ($STR) > $max) {
Die (' Maximum $max bytes ');
}
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 filtration, 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;
}
?>

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.