How to Prevent SQL Injection Analysis in PHP

Source: Internet
Author: User
Tags how to prevent sql injection
This article mainly introduces how to prevent SQL Injection Analysis in PHP, which is of great practical value. For more information, see

This article mainly introduces how to prevent SQL Injection Analysis in PHP, which is of great practical value. For more information, see

This article describes how to prevent SQL Injection in PHP. Share it with you for your reference. The specific analysis is as follows:

I. Problem description:

If the data entered by the user is inserted into an SQL query statement without being processed, the application may be vulnerable to SQL injection attacks, as shown in the following example:

The Code is as follows:

$ Unsafe_variable = $ _ POST ['user _ input'];

Mysql_query ("insert into 'table' ('column') VALUES ('". $ unsafe_variable ."')");

Because the user input may be like this:

The Code is as follows:

Value '); drop table table ;--

The SQL query will be changed to the following:

The Code is as follows:

Insert into 'table' ('column') VALUES ('value'); DROP table TABLE ;--')


Which effective methods should be taken to prevent SQL injection?

Ii. Solution Analysis:

Use pre-processing statements and parameterized queries. The pre-processing statements and parameters are sent to the database server for resolution. The parameters are processed as common characters. This method prevents attackers from injecting malicious SQL statements. You have two options to implement this method:

1. Use PDO:

The Code is 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. Use mysqli:

The Code is 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
}

3. PDO

Note that the use of PDO by default does not allow the MySQL database to execute the true pre-processing statement (the reason is described below ). To solve this problem, you should disable PDO to simulate preprocessing statements. An example of using PDO to create a database connection is as follows:

The Code 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 );


In the preceding example, the error reporting mode (ATTR_ERRMODE) is not required, but we recommend that you add it. In this way, when a Fatal Error occurs, the script does not stop running, but gives the programmer a chance to capture PDOExceptions to properly handle the Error. However, the first setAttribute () call is required. It prohibits PDO from simulating preprocessing statements. Instead, it uses a true preprocessing statement, that is, MySQL executes preprocessing statements. This ensures that the statements and parameters have not been processed by PHP before being sent to MySQL, which prevents attackers from injecting malicious SQL statements. For more information about the causes, see the previous article: Analysis of PDO anti-injection principles and precautions for using PDO. Note that in earlier versions of PHP (<5.3.6), you cannot set the character set on the DSN of the PDO constructor. For details, refer to: silently ignored the charset parameter.

Iv. Analysis

What happens when you send SQL statements to the database server for preprocessing and parsing? By specifying a placeholder (? Or name: name) in the preceding example to tell the database engine where you want to filter. When you call execute, the pre-processing statement will be combined with the parameter value you specified. The key point is here: the parameter value is combined with the parsed SQL statement, rather than the SQL string. SQL Injection contains malicious strings when constructing SQL statements by triggering scripts. Therefore, separating SQL statements from parameters prevents the risk of SQL injection. Any parameter value you send will be treated as a normal string and will not be parsed by the database server. Return to the example above. If the value of the $ name variable is 'sara'; delete from employees, the actual query is to find that the value of the name field in employees is 'sara '; DELETE records FROM employees. Another advantage of using pre-processing statements is that if you execute the same statement multiple times in the same database connection session, it will be parsed only once, which improves the execution speed. If you want to know how to insert data, see the following example (using PDO ):

The Code is as follows:

$ PreparedStatement = $ db-> prepare ('insert INTO table (column) VALUES (: column )');

$ PreparedStatement-> execute (array ('column' => $ unsafeValue ));

I hope this article will help you with PHP programming.

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.