Search code examples
phpmysqlsql-injection

preventing sql injection in php


If user input is inserting without modification from SQL query, then the application becomes vulnerable to SQL injection, like in the following example:

$unsafe_variable = $_POST['user_input']; 

mysql_query("INSERT INTO `table` (`column`) VALUES ('$unsafe_variable')");

That's because the user can input something like value '); DROP TABLE table;--, and the query becomes:

INSERT INTO `table` (`column`) VALUES('value'); DROP TABLE table;--')

What can be done to prevent this from happening?


Solution

  • There is extensive information through simple Google searches that can guide you in the right direction. To start though:

    DON'T USE MYSQL_* FUNCTIONS These are deprecated and will generate warnings. They are not even remotely good practice for modern web development.

    USE A DATABASE LIBRARY INSTEAD like PDO or MySQLi. There's plenty of tutorials to get you started and most importantly these libraries take care of SQL injection for you. So use them!