Skip to content

Instantly share code, notes, and snippets.

@mkober
Created February 13, 2012 20:47
Show Gist options
  • Save mkober/1820269 to your computer and use it in GitHub Desktop.
Save mkober/1820269 to your computer and use it in GitHub Desktop.
Ways to prevent SQL Injections in PHP (for LV PHP Meetup)
// Ways to prevent SQL Injections in PHP (http://php.net/manual/en/security.database.sql-injection.php)
1. "Never connect to the database as a superuser or as the database owner. Use always customized users with very limited privileges."
2. "Check if the given input has the expected data type. PHP has a wide range of input validating functions, from the simplest ones found in Variable Functions and in Character Type Functions" (e.g. is_numeric(), ctype_digit()
3. "Quote each non numeric user supplied value that is passed to the database with the database-specific string escape function" (e.g. mysql_real_escape_string(), sqlite_escape_string(), etc.). "If a database-specific string escape mechanism is not available, the addslashes() and str_replace() functions may be useful (depending on database type)."
<?php
settype($offset, 'integer');
$query = "SELECT id, name FROM products ORDER BY name LIMIT 20 OFFSET $offset;";
// please note %d in the format string, using %s would be meaningless
$query = sprintf("SELECT id, name FROM products ORDER BY name LIMIT 20 OFFSET %d;",$offset);
?>
4. "Do not print out any database specific information, especially about the schema, by fair means or foul."
5. "You may use stored procedures and previously defined cursors to abstract data access so that users do not directly access tables or views, but this solution has another impacts."
6. "Use PDO objects to clean the queries"
<?php
$preparedStatement = $db->prepare('SELECT * FROM employees WHERE name = :name');
$preparedStatement->execute(array(':name' => $name));
$rows = $preparedStatement->fetchAll();
?>
7. "Use a modern framework like Zend, CakePHP, ASP.NET, and Rails because the function to clean the incoming parameters is provided by default."
Other good references:
http://hakipedia.com/index.php/SQL_Injection
http://www.tizag.com/mysqlTutorial/mysql-php-sql-injection.php
http://www.unixwiz.net/techtips/sql-injection.html
http://shiflett.org/articles/sql-injection
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment