Page 1 of 1

How can I prevent SQL injection in PHP?

Posted: Mon Mar 17, 2014 6:51 am
by jangmi
If user input is inserted without modification into an SQL query, then the application becomes vulnerable to SQL injection, like in the following example:

Code: Select all

$unsafe_variable = $_POST['user_input']; 

Code: Select all

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:

Code: Select all

INSERT INTO table (column) VALUES('`**`value'); DROP TABLE table;--`**`')
What can be done to prevent this from happening?

Re: How can I prevent SQL injection in PHP?

Posted: Mon Mar 17, 2014 6:59 am
by Celauran
First of all, stop using mysql_ functions. They've been worst practice for years, are deprecated, and will be removed from the language. That said, the easiest way to prevent SQL injection is to use prepared statements.

Re: How can I prevent SQL injection in PHP?

Posted: Wed Sep 03, 2014 5:25 pm
by requinix
resonant wrote:EDIT: Wow, really? http://pastebin.com/6DxQcPrm <- because double htmlentities() is fail

Code: Select all

 tags are broken - use [syntax=php] instead.