How can I prevent SQL injection in PHP?

Discussions of secure PHP coding. Security in software is important, so don't be afraid to ask. And when answering: be anal. Nitpick. No security vulnerability is too small.

Moderator: General Moderators

Post Reply
jangmi
Forum Newbie
Posts: 11
Joined: Sat Mar 08, 2014 7:39 am

How can I prevent SQL injection in PHP?

Post 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?
User avatar
Celauran
Moderator
Posts: 6427
Joined: Tue Nov 09, 2010 2:39 pm
Location: Montreal, Canada

Re: How can I prevent SQL injection in PHP?

Post 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.
User avatar
requinix
Spammer :|
Posts: 6617
Joined: Wed Oct 15, 2008 2:35 am
Location: WA, USA

Re: How can I prevent SQL injection in PHP?

Post 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.
Post Reply