PHP to prevent SQL injection method, Phpsql injection detailed _php tutorial

Source: Internet
Author: User
Tags sql injection attack

PHP to prevent the SQL injection method in detail, phpsql injection of detailed


Problem Description:
If the data entered by the user is inserted into an SQL query statement without processing, then the application is likely to suffer a SQL injection attack, as in the following example:

Copy the Code code as follows:
$unsafe _variable = $_post[' user_input ');
mysql_query ("INSERT into ' table ' (' column ') VALUES (')." $unsafe _variable. "')");

Because the user's input might be this:

Copy the Code code as follows:
Value '); DROP TABLE table;--

Then the SQL query will become as follows:

Copy the Code code as follows:
INSERT into ' table ' (' column ') VALUES (' value '); DROP TABLE table;--')

What effective methods should be taken to prevent SQL injection?

Best Answer (from Theo):
Use preprocessing statements and parameterized queries. The preprocessing statements and parameters are sent to the database server for parsing, and the parameters are treated as ordinary characters. This approach prevented attackers from injecting malicious SQL. You have two options to implement this method:

1. Using PDO:

Copy the Code code as follows:
$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:

Copy the Code code as follows:
$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
Note that using PDO by default does not allow the MySQL database to execute a true preprocessing statement (for reasons below). To solve this problem, you should prohibit PDO from simulating pre-processing statements. A good example of using PDO to create a database connection is as follows:

Copy the Code code 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);

In the above example, the error mode (Attr_errmode) is not required, but it is recommended to add it. Thus, when a fatal error (Fatal error) occurs, the script does not stop running, but instead gives the programmer a chance to capture pdoexceptions in order to properly handle the error. However, the first setattribute () call is mandatory, and it prohibits PDO from simulating pre-processing statements, while using a true preprocessing statement that has MySQL to execute a preprocessing statement. This ensures that statements and parameters are not processed by PHP before they are sent to MySQL, which will make it impossible for an attacker to inject malicious SQL. To understand why, refer to this blog post: PDO anti-injection principle analysis and considerations for using PDO. Note in the old version of PHP (<5.3.6), you cannot set the CharSet on the DSN of the Pdo constructor, refer to: Silently ignored the charset parameter.

Analytical

What happens when you send SQL statements to the database server for preprocessing and parsing? Tell the database engine where you want to filter by specifying a placeholder (one? or the name in the example above: name). When you invoke execute, the preprocessing statement will be combined with the value of the parameter you specified. The key point is here: The value of the parameter is combined with the parsed SQL statement, not the SQL string. SQL injection is a malicious string that is included when the SQL statement is constructed by triggering a script. So, by separating the SQL statements and parameters, you prevent the risk of SQL injection. The value of any parameter you send will be treated as a normal string without being parsed by the database server. Back to the example above, if the value of the $name variable is ' Sarah '; DELETE from employees, then the actual query would be to look in employees for the Name field value ' Sarah '; DELETE from Employees Records. Another advantage of using preprocessing statements is that if you execute the same statement many times in the same database connection session, it will only be parsed once, which can increase the speed of execution. If you want to ask how to insert it, take a look at the following example (using PDO):

Copy the Code code as follows:
$preparedStatement = $db->prepare (' INSERT into table (column) VALUES (: Column) ');
$preparedStatement->execute (Array (' column ' = $unsafeValue));

http://www.bkjia.com/PHPjc/932482.html www.bkjia.com true http://www.bkjia.com/PHPjc/932482.html techarticle PHP to prevent SQL injection method in detail, Phpsql injection detailed description of the problem: if the user input data is inserted in an unhandled SQL query statement, then the application will likely ...

  • 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.