Prevent SQL Injection in PHP

By | December 10, 2012

Two easy ways to prevent SQL Injection in PHP

To many people still execute sql queries using methods which does not prevent SQL Injection, and many tutorials out there give bad example of doing so.

SQL Injection? What? -> SQL Injection explained

There are two easy aproachs to prevent SQL Injection:

  1. Using PDO:
    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:
    $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

If you are using MySQL and PDO the usage of prepared statements are emulated by PDO and you have to disable this feature to use REAL prepared statements.

Example of creating a connection using PDO:

$dbConnection = new PDO('mysql:dbname=exampledb;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 isn’t strictly necessary, but it is advised to add it. This way the script will not stop with a Fatal Error when something goes wrong. And gives the developer the chance to catchany error(s).

What is mandatory however is the setAttribute() line, which tells PDO to disable emulated prepared statements and use real prepared statements. This makes sure the statement and the values aren’t parsed by PHP before sending it the the MySQL server (giving a possible attacker no chance to inject malicious SQL).

Although you can set the charset in the options of the constructor it’s important to note that ‘older’ versions of PHP (< 5.3.6) silently ignored the charset parameter in the DSN.

Explanation

What happens is that the SQL statement you pass to prepare is parsed and compiled by the database server. By specifying parameters (either a ? or a named parameter like :name in the example above) you tell the database engine where you want to filter on. Then when you call execute the prepared statement is combined with the parameter values you specify.

The important thing here is that the parameter values are combined with the compiled statement, not a SQL string. SQL injection works by tricking the script into including malicious strings when it creates SQL to send to the database. So by sending the actual SQL separately from the parameters you limit the risk of ending up with something you didn’t intend. Any parameters you send when using a prepared statement will just be treated as strings (although the database engine may do some optimization so parameters may end up as numbers too, of course). In the example above, if the $name variable contains ‘Sarah’; DELETE * FROM employees the result would simply be a search for the string “‘Sarah’; DELETE * FROM employees”, and you will not end up with an empty table.

Another benefit with using prepared statements is that if you execute the same statement many times in the same session it will only be parsed and compiled once, giving you some speed gains.

[amazon_carousel widget_type="SearchAndAdd" width="600" height="200" title="Books" market_place="" shuffle_products="False" show_border="False" keywords="PHP" browse_node="" search_index="Books" /]

One thought on “Prevent SQL Injection in PHP

  1. Rafa

    Thanks – very nice example, and nice to see that you know better than most people and you actually use parameterized queries. Great!

    Another good one on sql injection prevention:

    preventing sql injection

    Reply

Leave a Reply