PHP prevents injection attack instance analysis and php injection instance analysis. Analysis of PHP injection attack prevention examples. This article analyzes php injection attack prevention methods in detail in the form of examples. Share it with you for your reference. The specific analysis is as follows: Analysis of PHP injection protection instances and analysis of php injection instances
This article analyzes in detail how PHP can prevent injection attacks in the form of examples. Share it with you for your reference. The specific analysis is as follows:
PHP addslashes () function -- escape with single apostrophes and diagonal lines
PHP String function
Definition and usage
The addslashes () function adds a backslash before the specified predefined character.
The predefined characters are:
Single quotes (')
Double quotation marks (")
Backslash (\)
NULL
Syntax:
Addslashes (string)
Parameters |
Description |
String |
Required. Specifies the string to be checked. |
Tips and comments
Tip: This function can be used to prepare suitable strings for strings stored in the database and database query statements.
Note: By default, the magic_quotes_gpc command of PHP is on, and addslashes () is automatically run for all GET, POST, and COOKIE data (). Do not use addslashes () for strings that have been escaped by magic_quotes_gpc, because this causes double-layer escape. In this case, you can use the get_magic_quotes_gpc () function for detection.
Example
In this example, we want to add a backslash to the predefined characters in the string:
The code is as follows:
<? Php
$ 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
The code is as follows:
Function html ($ str)
{
$ Str = get_magic_quotes_gpc ()? $ Str: addslashes ($ str );
Return $ str;
}
Get_magic_quotes_gpc:
Obtain the value of magic_quotes_gpc in the PHP environment variable.
Syntax: long get_magic_quotes_gpc (void );
Return value: long integer
Function type: PHP system function
Description:
This function obtains the magic_quotes_gpc (GPC, Get/Post/Cookie) value set in the PHP environment. If the return value is 0, this function is disabled. if the return value is 1, this function is enabled. When magic_quotes_gpc is enabled, all '(single quotation marks),' (double quotation marks), \ (backslash) and null characters are automatically converted to overflow characters containing the backslash.
Addslashes -- use a backslash to reference a string
Description:
String addslashes (string str)
Returns a string that requires a backslash before certain characters for database query statements. These characters are single quotation marks ('), double quotation marks ("), backslash (\), and NUL (NULL ).
An example of using addslashes () is when you want to input data into the database. For example, insert the name 'Reilly into the database, which requires escaping. Most databases use \ as the escape character: O \ 'Reilly. In this way, the data can be put into the database without inserting additional \. When the PHP command magic_quotes_sybase is set to on, it means that when 'is inserted,' is used for escape.
By default, the PHP command magic_quotes_gpc is on, which automatically runs addslashes () on all GET, POST, and COOKIE data (). Do not use addslashes () for strings that have been escaped by magic_quotes_gpc, because this causes double-layer escape. In this case, you can use the get_magic_quotes_gpc () function for detection.
Example 1. addslashes () example
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 gets the magic_quotes_gpc (GPC, Get/Post/Cookie) value of the variable configured in the PHP environment. If 0 is returned, this function is disabled. if 1 is returned, this function is enabled. When magic_quotes_gpc is enabled, all '(single quotation marks),' (double quotation marks), \ (backslash) and null characters are automatically converted to overflow characters containing the backslash.
Magic_quotes_gpc
For magic_quotes_gpc in php. ini, is it set to off or on?
Personal opinion, should be set to on
Summary:
1. for magic_quotes_gpc = on,
We may not use the string data of the input or output database
The operation of addslashes () and stripslashes () will also display the data normally.
If you perform addslashes () processing on the input data,
In this case, you must use stripslashes () to remove unnecessary backslash.
2. 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 backslash together into the database, it only helps mysql to complete SQL statement execution.
Supplement:
Magic_quotes_gpc: WEB client server; TIME: When the request starts, for example, when the script is running.
Magic_quotes_runtime: The data read from the file, the exec () execution result, or the result obtained from the SQL query. function Time: The data generated every time the script accesses the running state.
Code:
The code is as follows:
<? Php
/*
Sometimes there are more than one variable to be submitted in a form. There may be a dozen or dozens of variables. Is it a little trouble to copy/paste the addslashes () at a time? Because the data obtained from the form or URL is in the form of an array, such as $ _ POST, $ _ GET), you can customize a function that can "scan the Army ".
*/
Function quotes ($ content)
{
// If magic_quotes_gpc = Off, start processing
If (! Get_magic_quotes_gpc ()){
// Determine whether $ content is an array
If (is_array ($ content )){
// If $ content is an array, it will process every single
Foreach ($ content as $ key => $ value ){
$ Content [$ key] = addslashes ($ value );
}
} Else {
// If $ content is not an array, it will be processed only once.
Addslashes ($ content );
}
} Else {
// If magic_quotes_gpc = On, it will not be processed
}
// Returns $ content
Return $ content;
}
?>
I hope this article will help you with PHP programming.
What is the best way to prevent SQL injection in php?
If you input a query directly inserted into an SQL statement, the application will be vulnerable to SQL injection. for example: $ unsafe_variable = $ _ POST ['User _ input']; mysql_query ("insert into table (column) VALUES ('". $ unsafe_variable. "')"); this is because you can enter a VALUE similar to "); drop table;-to convert the query to: Use predefine statements and parameterized queries. SQL statements with any parameters will be sent to the database server and parsed! It is impossible for attackers to maliciously inject SQL statements! 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 when you use PDO to access the MySQL database, the true pre-definition statements are not used by default! To solve this problem, you must disable the statements prepared by simulation. Example of using PDO to create a connection: $ 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 ); in the preceding example, the error mode ERRMODE is not strictly required, but we recommend that you add it. This method does not stop when an error occurs and a fatal error occurs. And give developers the opportunity to capture any errors (when a PDOException exception is thrown ). The setAttribute () line is mandatory. it tells PDO to disable the simulation of the pre-definition statement and use the real pre-definition statement. This ensures that the statements and values are not parsed by PHP before being sent to the MySQL database server (attackers have no chance to inject malicious SQL statements ). of course, you can set character set parameters in the constructor options. Note that the 'old' PHP version (5.3.6) ignores character set parameters in DSN. The most important thing here is that this parameter value is combined with a pre-compiled statement, rather than an SQL string. the operating principle of SQL injection is that the SQL script created by Deception includes malicious string sending ...... remaining full text>
[Reprint] how to prevent php SQL injection attacks
In my opinion, the most important thing 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, php scripts do not output errors on web pages, so that attackers can analyze the information. When calling mysql functions such as mysql_query, add @, I .e. @ mysql_query (...), so that mysql errors will not be output. Similarly, attackers may not analyze useful information. In addition, some programmers are used to output errors and SQL statements when mysql_query errors occur during development, such as: $ t_strSQL = "SELECT a from B ....";
If (mysql_query ($ t_strSQL) {// correct processing} else {echo "error! SQL statement: $ t_strSQL \ r \ n error message ". mysql_query (); exit;} this method is quite dangerous and stupid. If you have to 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
// In the call script:
Php/************************* instructions: determine whether the passed variables contain invalid characters such as $ _ POST and $ _ GET: anti-injection ************************ // The illegal character to be filtered $ ArrFiltrate = array ("'", ";", "union"); // url to be redirected after an error occurs. If this parameter is left blank, $ StrGoUrl = ""; // whether the value 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 to start foreach ($ ArrPostAndGet as $ key =>$ value) {if (FunStringExist ($ value, $ ArrFiltrate) {echo "alert (\" invalid character \ ");"; if (empty ($ StrGoUrl )) {echo & q ...... remaining full text>
In this article, we analyze in detail how PHP prevents injection attacks in the form of examples. Share it with you for your reference. The specific analysis is as follows :...