How to Prevent SQL Injection in PHP?

Problem Description:

If user input data is inserted into an SQL query without proper handling, the application is likely vulnerable to SQL injection attacks, as shown in the following example:


  1. $unsafe_variable = $_POST['user_input'];   
  2.    
  3. mysql_query("INSERT INTO `table` (`column`) VALUES ('" . $unsafe_variable . "')");   


  1. value'); DROP TABLE table; 

SQL:


  1. INSERT INTO `table` (`column`) VALUES('value'); DROP TABLE table;–') 

SQL?

Theo):

。,。SQL。 :

1、PDO:


  1. $stmt = $pdo->prepare('SELECT * FROM employees WHERE name = :name');  
  2.    
  3. $stmt->execute(array('name' => $name));  
  4.    
  5. foreach ($stmt as $row) {  
  6.     // do something with $row  

2、mysqli:


  1. $stmt = $dbConnection->prepare('SELECT * FROM employees WHERE name = ?');  
  2. $stmt->bind_param('s', $name);  
  3.    
  4. $stmt->execute();  
  5.    
  6. $result = $stmt->get_result();  
  7. while ($row = $result->fetch_assoc()) {  
  8.     // do something with $row  
PDO

,PDOMySQL()。,PDO。PDO:


  1. $dbConnection = new PDO('mysql:dbname=dbtest;host=127.0.0.1;charset=utf8''user''pass');  
  2.    
  3. $dbConnection->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);  
  4. $dbConnection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); 

,(ATTR_ERRMODE),。,(Fatal Error),,PDOExceptions,。 ,setAttribute(),PDO,,MySQL。MySQLPHP,SQL。,:PDOPDO。 PHP(<5.3.6),PDODSNSettings,:silently ignored the charset parameter

SQL?(? :name),。execute,。 :SQL,SQL。SQLSQL。,SQL,SQL。,。,$name ’Sarah’; DELETE FROM employees , employees name  ’Sarah’; DELETE FROM employees 。 :,,。 ,(PDO):


  1. $preparedStatement = $db->prepare('INSERT INTO table (column) VALUES (:column)');  
  2.    
  3. $preparedStatement->execute(array('column' => $unsafeValue)); 

: StackOverflow   :  – rokety

: http://blog.jobbole.com/67875/

Leave a Comment

Your email address will not be published.