PHP data filter function_PHP tutorial

WBOY
Release: 2016-07-13 10:36:57
Original
910 people have browsed it

1. Basic principles of PHP submission data filtering

1) When submitting variables into the database, we must use addslashes() for filtering. For example, our injection problem can be solved with just one addslashes(). In fact, when it comes to variable values, the intval() function is also a good choice for filtering strings.

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 into slashes. magic_quotes_runtime can play a formatting role in data entering and exiting the database. In fact, this parameter was very popular back in the old days when injection was crazy.

3) When using system functions, you must use escapeshellarg() and escapeshellcmd() parameters to filter, so that you can use system functions with confidence.

4) For cross-site, the two parameters of strip_tags() and htmlspecialchars() are good, and the tags with html and php submitted by users will be converted. For example, angle brackets "<" will be converted into harmless characters such as "<".

代码如下
$new = htmlspecialchars("Test", ENT_QUOTES);
strip_tags($text,);

5) Regarding the filtering of related functions, just like the previous include(), unlink, fopen(), etc., as long as you specify the variables you want to perform the operation or filter the related characters strictly, I think this will be enough. Impeccable.

2. Simple data filtering with PHP

1) Storage: trim($str),addslashes($str)

 2) Output: stripslashes($str)

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

Look at the following example for further discussion of the dispatch.php script:

The code is as follows

代码如下

/* 全局安全处理 */

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;
}

?>

/* 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, you can be sure that the program is designed to ensure that the initial global security handling cannot be bypassed. It also makes it easy for developers to see the control flow of specific tasks. For example, it is easy to know without browsing the entire code: when $form_valid is true, end.inc is the only one displayed to the user; since it is before process.inc is included and has just been initialized to false, 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 an associated error message).

Attention

If you use a directory-directed file such as index.php (instead of dispatch.php), you can use the URL address 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.

Contains methods

Another way is to use a single module, which is responsible for all security processing. This module is included at the front (or very front) of all public 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;
}

?>

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';
}

 代码如下  


Username:


Password:



break;
}

?> In this example, each submitted form is considered to contain the unique verification value form, and security.inc independently processes the data in the form that needs to be filtered. The HTML form that implements this requirement looks like this:

The array called $allowed is used to check which form variables are allowed. This list should be consistent before the form is processed. Process control decides what to execute, and process.inc is where the actual filtered data arrives.

Attention

A good way to ensure that security.inc is always included at the beginning of every script is to use the auto_prepend_file setting.

Example of filtering

Establishing a whitelist is very important for data filtering. Since it's impossible to give examples for every type of form data you may encounter, some examples can help you get a general understanding.

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'];
}

?>

$clean = array();

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

if (preg_match($email_pattern, $_POST[ 'email']))
{
$clean['email'] = $_POST['email'];
}

 代码如下  

$clean = array();

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

?>

?> 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;
}<🎜>

?>

  下面的代码确保$_POST['num']是一个整数(integer):

 代码如下  

代码如下

$clean = array();

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

?>

$clean = array();

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

?>

 代码如下  

$clean = array();

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

?>

  下面的代码确保$_POST['num']是一个浮点数(float):
 代码如下  

$clean = array();<🎜>

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

?>

Name conversion

Each of the previous examples used the array $clean. This is a good practice for developers to determine if their data is potentially compromised. Never save data in $_POST or $_GET after validating it. As a developer, you should always be fully suspicious of data saved in super global arrays.

It should be added that using $clean can help to think about what has not been filtered, which is more similar to the function of a whitelist. Can improve the level of security.

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

Timing

Once the PHP script starts executing, it means that all HTTP requests have ended. 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 register_globals is turned on). This is why initializing variables is a very good practice.

Anti-injection

The code is as follows

//PHP whole site anti-injection program, you need to require_once this file in the public file
//Judge 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 recursively
if (is_array ( $array )) {
foreach ( $array as $k => $v ) {
$array [$k] = sec ( $v );
}
} else if (is_string ( $array )) {
//Use addslashes function to process
$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!' );
} //Judge whether it is empty
else if (inject_check ( $id )) {
die ('Illegal parameter');
} //Inject judgment
else if (! is_numetic ( $id )) {
die ('Illegal parameter');
}
//Number judgment
$id = intval ( $id );
//Integer
return $id;
}
//Character filter function
function str_check($str) {
if (inject_check ( $str )) {
die ('Illegal parameter');
}
//Inject 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 bytes');
} else if (isset ( $max ) && strlen ( $str ) > $max) {
die ('up to $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 performs filtering and prevents 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;
}
?>

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/737681.htmlTechArticle1. Basic principles of PHP submission data filtering 1) When submitting variables into the database, we must use addslashes() Filtering, like our injection problem, can be solved with just addslashes(). Its...
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!