I just had a friend of mine look over some code I’m using to get data from my database, and he tells me it’s very unsecure and that SQL injection is serious shit.
Here’s the code I’m using now:
$id = $_GET['id'];
$result = mysql_query("SELECT * FROM news WHERE id = $id") or die("err0r");
He tells me that the solution is to change that code into:
$id = intval($_GET['id']);
$result = mysql_query("SELECT * FROM news WHERE id = $id") or die("err0r");
My code somehow (according to my friend) makes any user able to edit content in my database:
http://mydomain.com/?p=news&id=38;DROP TABLE tablename;
Could someone explain exactly what he means?
Thank you and have a pleasant day
Consider what would happen if someone posted
http://www.mydomain.com?id=1; DROP TABLE newsOlder versions of PHP tried to automatically protect against this sort of thing by automatically escaping all the input variables; ie by adding slashes to any quote characters in the input so that they wouldn’t break a SQL query. This is no longer the default in current versions of PHP since it caused a lot of other issues.
However in your case, you haven’t even quoted the variable in the SQL query, so even that protection wouldn’t have helped you since a hacker wouldn’t have needed to include any quotes to hack you.
The
intval()solution will indeed help you in this specific case, but it won’t help in others (eg if you need to handle a string variable).The correct solution:
You should use the
mysql_real_escape_string()function on all variables that are to be passed into the SQL query to prevent any possible hack attacks, like so:You should enclose all variables in the SQL string in quotes, like this:
By the way… This comic strip is a very popular thing to link to to demonstrate the problem. 😉