MySQL injection protection and vulnerability signs using PHP

You have to sanitize all input. How you can do this depends on the programming languaguage and/or framework you are working with.

edit:

If you are using php the function you are looking for is mysql_real_escape_string($string). You should use that on everything you receive from the client that should go in the database.


If you're not using a framework that provides you with sanitizing tools PHP has a built in string escaper, you should start there. You can find the documentation on that within the PHP docs for mysql real escape string. If you look at example three you'll get a good idea of the basics you can follow.

Another method I follow is to make sure I cast variables where appropriate. For example if I'm expecting input from a user to be an integer I'll do the following:

$age = (int)$age;

Also if a column is supposed to be limited to one or two values (for example a gender column) make sure you enforce that in your PHP before putting it into the database.


Use prepared statements instead of mixing the statement and the actual payload data.

see

  • http://dev.mysql.com/tech-resources/articles/4.1/prepared-statements.html
  • PDO::prepare
  • mysqli::prepare

You might also be interested in http://shiflett.org/articles/sql-injection and http://shiflett.org/blog/2007/sep/the-unexpected-sql-injection


Trust no one!

Sanitize all input -- filter_var() or regexes or in_array() of valid values or a mixed strategy depending on datatype.

"Input" means any source of input that you don't directly control -- not just forms!

Sanitize anything you get back from $_GET, $_POST, $_SESSION, $_COOKIE -- anything that could have any possibility of being tainted.

AND

Use prepared statements