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

Source: Internet
Author: User

If you input a query directly inserted into an SQL statement, the application will be vulnerable to SQL injection. For example:

Copy codeThe Code is as follows: $ unsafe_variable = $ _ POST ['user _ input'];
Mysql_query ("insert into table (column) VALUES ('". $ unsafe_variable ."')");

This is because you can enter a TABLE similar to VALUE "); drop table;-To convert the query:Copy codeThe Code is as follows: insert into table (column) VALUES ('value'); drop table table ;'

How should we prevent this situation?See the following
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 ):
Copy codeThe 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:
Copy codeThe 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
}

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.
An example of using PDO to create a connection is as follows:
Copy codeThe 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 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.

Explanation)
What happens when the SQL prepared statements you pass are parsed and compiled by the database server? Use the specified character (in the preceding example, it is like? Or: name) tells the database engine What You Want to filter, and then calls execute to execute the prepared statement combined with the parameter value you specified.

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 SQL scripts created by spoofing methods include malicious Strings sent to the database. therefore, by sending actual separate SQL parameters, you will reduce the risk. when using prepared statements, any parameters you send will only be treated as strings (although the database engine may optimize some parameters, of course, it may eventually be numbers ). in the above example, if the variable $ name contains 'sara'; DELETE * FROM employees, the result will only be a search string "'sara'; DELETE * FROM employees ", you will not get an empty table.

Another benefit of using prepared statements is that if you execute the same statement multiple times in the same session, this will only be parsed and compiled once, giving you some speed increase.
Oh, since you asked how to insert, here is an example (using PDO ):

Copy codeThe Code is as follows: $ preparedStatement = $ db-> prepare ('insert INTO table (column) VALUES (: column )');
$ PreparedStatement-> execute (array (': column' => $ unsafeValue ));

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.