PHP Prevent injection attack case analysis, PHP injection example Analysis _php tutorial

Source: Internet
Author: User
Tags sql injection attack stmt

PHP Prevent injection attack case analysis, PHP injection Example analysis


In this paper, the method of preventing injection attack by PHP is analyzed in detail. Share to 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 character.
These predefined characters are:
Single quotation mark (')
Double quotation marks (")
Back slash (\)
Null
Grammar:

Addslashes (String)

Parameters Describe
String Necessary. Specifies the string to check.

Hints and Notes

Tip: This function can be used to prepare the appropriate string for strings stored in the database and for database query statements.
Note: By default, PHP instruction MAGIC_QUOTES_GPC is on, and automatically runs Addslashes () for all GET, POST, and COOKIE data. Do not use Addslashes () for strings that have been MAGIC_QUOTES_GPC escaped, because this results in double-layer escaping. You can use the function GET_MAGIC_QUOTES_GPC () to detect this situation.

Example

In this case, we're going to add a backslash to the predefined characters in the string:
Copy the Code code as follows: <?php
$str = "Who ' s John Adams?";
Echo $str. "This was not safe in a database query.
";
echo addslashes ($STR). "This is safe in a database query.";
?>
Output:
Who ' s John Adams? This is the not safe in a database query.
Who\ ' s John Adams? This is safe in a database query.

GET_MAGIC_QUOTES_GPC function

Copy the Code code as follows: function html ($STR)
{
$str = GET_MAGIC_QUOTES_GPC () $str: Addslashes ($STR);
return $str;
}

GET_MAGIC_QUOTES_GPC:
Gets 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 functions

Content Description:

This function obtains the variable MAGIC_QUOTES_GPC (GPC, Get/post/cookie) value set by the PHP environment. Returning 0 means turning off this function, and returning 1 indicates that this function is turned on. When MAGIC_QUOTES_GPC is turned on, all the ' (single quotes), ' (double quotes), \ (backslash) and null characters are automatically converted to overflow characters that contain backslashes.

addslashes --use a backslash to reference a string

Describe:

String addslashes (String str)
Returns a string that is preceded by a backslash in order for the database query statement to be preceded by some characters. These characters are single quotes ('), double quotation marks ("), backslashes (\), and NUL (the NULL character).

An example of using addslashes () is when you want to enter data into the database. For example, the name O ' Reilly is inserted into the database, which needs to be escaped. Most databases use \ as escape character: O\ ' Reilly. This allows the data to be placed in the database without inserting additional \. When PHP instruction Magic_quotes_sybase is set to ON, it means that the insert ' will be used ' to escape.

By default, PHP instruction MAGIC_QUOTES_GPC is on, and it is primarily for all GET, POST, and COOKIE data automatically run Addslashes (). Do not use Addslashes () for strings that have been MAGIC_QUOTES_GPC escaped, because this results in double-layer escaping. You can use the function GET_MAGIC_QUOTES_GPC () to detect this situation.

Example 1. Addslashes () example
Copy the code 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 PHP environment configuration variable MAGIC_QUOTES_GPC (GPC, Get/post/cookie) value. Returns 0 to turn off this function; return 1 indicates that this function is turned on. When MAGIC_QUOTES_GPC is turned on, all the ' (single quotes), ' (double quotes), \ (backslash) and null characters are automatically converted to the overflow character that contains the backslash.

Magic_quotes_gpc

For MAGIC_QUOTES_GPC in PHP.ini, is it set to off or on?

Personal view, should be set to ON

Summarized as follows:

1. In the case of Magic_quotes_gpc=on,

We can not make the string data of the input and output database
Addslashes () and Stripslashes (), the data will also be displayed normally.

If you do a addslashes () processing of the input data at this time,
Then you must use Stripslashes () to remove the extra backslash when outputting.

2. In the case of Magic_quotes_gpc=off

The input data must be processed using addslashes (), but does not require the use of stripslashes () to format the output
Because Addslashes () did not write the backslash to the database, it only helped MySQL complete the execution of the SQL statement.

Add:

The scope of MAGIC_QUOTES_GPC is: Web client server; Action time: When the request starts, for example when the script is running.
Magic_quotes_runtime: Data read from a file or executed by exec () or from a SQL query; time: Every time the script accesses the data generated in the running state

Code:

Copy the Code code as follows: <?php
/*
Sometimes a form submits more than one variable, and there can be more than 10 or dozens of of these. Copy/Paste the addslashes () once and again, is it a bit of a hassle? Since the data obtained from the form or URL is in the form of an array, such as $_post, $_get, then customize a function that can "annihilation"
*/
function quotes ($content)
{
If Magic_quotes_gpc=off, then start processing
if (!GET_MAGIC_QUOTES_GPC ()) {
Determine if the $content is an array
if (Is_array ($content)) {
If $content is an array, then it is processed by every single
foreach ($content as $key = = $value) {
$content [$key] = addslashes ($value);
}
} else {
If $content is not an array, it is processed only once
Addslashes ($content);
}
} else {
If magic_quotes_gpc=on, then do not deal with
}
Back to $content
return $content;
}
?>

I hope this article is helpful to everyone's PHP programming.


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

If the user enters a query that is inserted directly into an SQL statement, the application is 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 similar value "); DROP table tables; -To make the query: use a pre-defined statement and a parameterized query. SQL statements with any parameters will be sent to the database server and parsed! It is impossible for an attacker to inject SQL into a malicious way! There are two basic options for achieving this: 1. Using 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. Using 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 ()) {//does something with $row}pdo (PHP data Object) Note When using PDO to access the MySQL database The true pre-defined statement is not used by default! To solve this problem, you must disable the prepared statements for emulation. Examples of creating a connection using PDO are 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-&GT;setattribute (Pdo::attr_errmode, pdo::errmode_exception); In the above example, the error mode Errmode is not strictly necessary, but it is recommended to add it. This method script does not stop when there is a fatal error in running an error. and give developers the opportunity to catch any errors (when throwing pdoexception exceptions). SetAttribute () That line is mandatory, it tells PDO to disable the emulation of the pre-defined statements, using the real pre-defined statements. This ensures that statements and values are not parsed by PHP before being sent to the MySQL database server (the attacker has no opportunity to inject malicious SQL). Of course you can set the character set parameters in the constructor options, paying special attention to the ' old ' PHP version (5.3.6) that ignores character set parameters in the DSN. The most important thing here is that the parameter value is combined with a precompiled statement instead of a SQL string. SQL injection works by spoofing the creation of SQL scripts including malicious string hair ... Remaining full text >>

[Reprint] How to prevent PHP SQL injection attack

I think the most important thing is to check and escape the data type. The following rules are summarized: The display_errors option in php.ini should be set to Display_errors = off. In this way, the PHP script does not output errors in the Web page after the error, so that the attacker could parse out the information. When you call a MySQL function such as mysql_query, you should precede it with @, which is @mysql_query (...) so that the MySQL error is not output. In the same vein, the attacker is not allowed to parse out useful information. In addition, some programmers in the development, when mysql_query error, used to output errors and SQL statements, such as: $t _strsql = "Select a from B ...";
if (mysql_query ($t _strsql)) {//Correct handling}else{echo "Error! SQL statement: $t _strsql \ r \ n error message ". mysql_query (); exit;} This practice is quite dangerous and foolish. If you must do this, it is best to set a global variable or define a macro in the configuration file of the Web site, set the debug flag: In the global configuration file:
Define ("Debug_mode", 0); 1:debug MODE; 0:release MODE
In the call script:

PHP/************************* Description: Determine whether the passed variable contains illegal characters such as $_post, $_get function: Anti-injection **************************///illegal character to filter $ Arrfiltrate=array ("'", ";", "union"); The URL to jump after the error, do not fill in the default previous page $strgourl= ""; Whether there is a value in the Array 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;}} Verify start of foreach ($ArrPostAndGet as $key + $value) {if (Funstringexist ($value, $ArrFiltrate)) {echo "alert (\" illegal character \ ");"; if (empty ($STRGOURL)) {echo &q ... Remaining full text >>

http://www.bkjia.com/PHPjc/904916.html www.bkjia.com true http://www.bkjia.com/PHPjc/904916.html techarticle PHP Anti-injection attack case analysis, PHP injection Example analysis in this paper, in detail, the method of PHP to prevent injection attacks. Share to everyone for your reference. The specific analysis is as follows: ...

  • Related Article

    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.