Home > Backend Development > PHP Tutorial > PHP injection attack prevention example analysis, PHP injection example analysis_PHP tutorial

PHP injection attack prevention example analysis, PHP injection example analysis_PHP tutorial

WBOY
Release: 2016-07-13 10:15:24
Original
850 people have browsed it

PHP injection attack prevention example analysis, PHP injection example analysis

This article provides a detailed analysis of PHP's methods of preventing injection attacks in the form of examples. Share it with everyone for your reference. The specific analysis is as follows:

PHP addslashes() function --single apostrophe plus slash escape

PHP String Function

Definition and usage

The addslashes() function adds a backslash before the specified predefined characters.
These predefined characters are:
Single quote (')
Double quotes (")
Backslash ()
NULL
Syntax:

addslashes(string)

Parameters Description
参数  描述
string 必需。规定要检查的字符串。
string Required. Specifies the string to check.

Tips and Notes

Tip: This function can be used to prepare appropriate strings for strings stored in the database and database query statements.
Note: By default, the PHP directive magic_quotes_gpc is on, automatically running addslashes() on all GET, POST and COOKIE data. Do not use addslashes() on strings that have been escaped by magic_quotes_gpc, as this will result in double escaping. When encountering this situation, you can use the function get_magic_quotes_gpc() to detect it.

Example

In this example, we want to add a backslash to a predefined character in the string:

Copy code The code is as follows:
$str = "Who's John Adams?";
echo $str . " This is not safe in a database query.
";
echo addslashes($str) . " This is safe in a database query.";
?>

Output:
Who's John Adams? This is not safe in a database query.
Who's John Adams? This is safe in a database query.

get_magic_quotes_gpc function

Copy code The code is as follows:
function html($str)
{
$str = get_magic_quotes_gpc()?$str:addslashes($str);
Return $str;
}

get_magic_quotes_gpc:
Get the value of the PHP environment variable magic_quotes_gpc.
Syntax: long get_magic_quotes_gpc(void);
Return value: long integer
Function type: PHP system function

Content description:

This function obtains the value of the variable magic_quotes_gpc (GPC, Get/Post/Cookie) set in the PHP environment. Returning 0 means turning off this function; returning 1 means turning this function on. When magic_quotes_gpc is enabled, all ' (single quote), " (double quote), (backslash) and null characters will be automatically converted to overflow characters containing backslash.

addslashes --Use backslashes to quote strings

Description:

string addslashes ( string str)
Returns a string with backslashes added in front of certain characters for the purpose of database query statements, etc. These characters are single quote ('), double quote ("), backslash () and NUL (NULL character).

An example of using addslashes() is when you are entering data into a database. For example, inserting the name O'reilly into the database requires escaping it. Most databases use as escape character: O'reilly. This puts the data into the database without inserting extra . When the PHP directive magic_quotes_sybase is set to on, it means that inserting ' will be escaped with '.

By default, the PHP instruction magic_quotes_gpc is on, which mainly automatically runs addslashes() on all GET, POST and COOKIE data. Do not use addslashes() on strings that have been escaped by magic_quotes_gpc, as this will result in double escaping. When encountering this situation, you can use the function get_magic_quotes_gpc() to detect it.

Example 1. addslashes() example

Copy code The code is as follows:
$str = "Is your name O'reilly?";
// Output: Is your name O'reilly?
echo addslashes($str);
?>
get_magic_quotes_gpc()

This function obtains the value of the variable magic_quotes_gpc (GPC, Get/Post/Cookie) in the PHP environment configuration. Returning 0 means turning off this function; returning 1 means turning this function on. When magic_quotes_gpc is turned on, all ' (single quote), " (double quote), (backslash) and null characters will automatically be converted to overflow characters containing backslash.

magic_quotes_gpc

For magic_quotes_gpc in php.ini, should it be set to off or on?

Personal opinion, should be set to on

The summary is as follows:

1. For magic_quotes_gpc=on,

We can not do anything with the string data of the input and output databases
For the operations of addslashes() and stripslashes(), the data will be displayed normally.

If you perform addslashes() on the input data at this time,
Then you must use stripslashes() to remove excess backslashes when outputting.

2. For the case of magic_quotes_gpc=off

You must use addslashes() to process the input data, but you do not need to use stripslashes() to format the output
Because addslashes() does not write the backslashes into the database, it just helps mysql complete the execution of the sql statement.

Supplement:

magic_quotes_gpc Scope is: WEB client server; Time of action: When the request starts, such as when the script is running.
magic_quotes_runtime Scope: Data read from a file or the result of executing exec() or obtained from a SQL query; Time of action: Every time the script accesses data generated in the running state

Code:

Copy code The code is as follows:
/*
Sometimes there is more than one variable submitted in a form, maybe a dozen or dozens. So is it a little troublesome to copy/paste addslashes() again and again? Since the data obtained from the form or URL appears in the form of an array, such as $_POST, $_GET), then customize a function that can "sweep the army"
*/
function quotes($content)
{
//If magic_quotes_gpc=Off, then start processing
if (!get_magic_quotes_gpc()) {
//Determine whether $content is an array
if (is_array($content)) {
//If $content is an array, then process each of its elements
foreach ($content as $key=>$value) {
$content[$key] = addslashes($value);
}
} else {
//If $content is not an array, then it will only be processed once
addslashes($content);
}
} else {
//If magic_quotes_gpc=On, then it will not be processed
}
//Return $content
return $content;
}
?>

I hope this article will be helpful to everyone’s PHP programming design.

What is the best way to prevent SQL injection in php?

If the user input is a query that is inserted directly into a SQL statement, the application will be vulnerable to SQL injection, such as the following example: $unsafe_variable = $_POST['user_input']; mysql_query("INSERT INTO table ( column) VALUES ('" . $unsafe_variable . "')"); This is because the user can enter something like VALUE "); DROP TABLE table; - , making the query become: Use prepared statements and parameterized queries. SQL statements with any parameters will be sent to the database server and parsed! It is impossible for an attacker to maliciously inject SQL! There are basically two options to achieve this goal: 1. Use PDO (PHP Data Objects): $stmt = $pdo->prepare('SELECT * FROM employees WHERE name = :name'); $stmt->execute(array(':name' => $name)); foreach ($stmt as $ row) { // do something with $row }2. Use mysqli:$stmt = $dbConnection->prepare('SELECT * FROM employees WHERE name = ?'); $stmt->bind_param('s', $ name); $stmt->execute(); $result = $stmt->get_result(); while ($row = $result->fetch_assoc()) { // do something with $row }PDO(PHP Data Object) Note that real prepared statements are not used by default when using PDO! To solve this problem, you must disable emulation of prepared statements. An example of using PDO to create a connection is as follows: $dbConnection = new PDO(' mysql:dbname=dbtest;host=127.0.0.1;charset=utf8', 'user', 'pass'); $dbConnection->setAttribute(PDO::ATTR_EMULATE_PREPARES, false); $dbConnection->setAttribute(PDO: :ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);The error mode ERRMODE is not strictly required in the above example, but it is recommended to add it. This method does not stop the script when a fatal error occurs. And give the developer a chance to catch any errors (when PDOException is thrown). The setAttribute() line is mandatory, it tells PDO to disable emulated prepared statements and use real prepared statements. This ensures that statements and values ​​are not parsed by PHP before being sent to the MySQL database server (an attacker has no chance of injecting malicious SQL). Of course you can set the character set parameter in the constructor options, paying special attention to 'old' PHP versions ( 5.3.6) will ignore the character set parameter in the DSN. The most important thing here is that the parameter value is combined with a precompiled statement, not with a SQL string. The working principle of SQL injection is that the SQL script created by deception includes a malicious string... The rest of the full text>>

[Repost] How to prevent PHP SQL injection attacks

I think the most important point is to check and escape data types. The following rules are summarized: The display_errors option in php.ini should be set to display_errors = off. In this way, after an error occurs in the php script, the error will not be output on the web page to prevent attackers from analyzing useful information. When calling mysql functions such as mysql_query, @ should be added in front, that is, @mysql_query(...), so that mysql errors will not be output. The same is true to prevent attackers from analyzing useful information. In addition, some programmers are used to outputting errors and sql statements when mysql_query errors when developing, for example: $t_strSQL = "SELECT a from b....";
if ( mysql_query($t_strSQL) ){ //Correct processing}else{echo "Error! SQL statement: $t_strSQL \r\nError message".mysql_query();exit;} This approach is quite dangerous and stupid. If you must do this, it is best to set a global variable or define a macro in the website configuration file and set the debug flag: In the global configuration file:
define("DEBUG_MODE",0); // 1: DEBUG MODE; 0: RELEASE MODE
//Calling script:

php /****************************** Description : Determine whether the passed variables contain illegal characters such as $_POST, $_GET Function: Anti-injection**************************/ //Required Filtered illegal characters $ArrFiltrate=array("'",";","union"); //The url to be jumped after an error occurs. If not filled in, the previous page will be defaulted. $StrGoUrl=""; //Whether there is an array The value in function FunStringExist($StrFiltrate,$ArrFiltrate){ foreach ($ArrFiltrate as $key=>$value){ if (eregi($value,$StrFiltrate)){ returntrue; } } returnfalse; } //Merge $ _POST and $_GETif(function_exists(array_merge)){ $ArrPostAndGet=array_merge($HTTP_POST_VARS,$HTTP_GET_VARS); }else{ foreach($HTTP_POST_VARS as $key=>$value){ $ArrPostAndGet[]=$value; } foreach ($HTTP_GET_VARS as $key=>$value){ $ArrPostAndGet[]=$value; } } //Verification starts foreach($ArrPostAndGet as $key=>$value){ if (FunStringExist($value,$ArrFiltrate )){ echo "alert(\"Illegal character\");"; if (empty($StrGoUrl)){ echo &q...The rest of the text>>

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/904916.htmlTechArticlePHP prevent injection attack example analysis, php injection example analysis This article analyzes in detail how PHP prevents injection attacks in the form of examples . Share it with everyone for your reference. The specific analysis is as follows:...
Related labels:
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