home ‣ Avoiding SQL injection bugs in PHP login
This tip is taken from this blog post.
SQL injection is a class of security problems in web applications caused by executing sql queries containing user-supplied text e.g. entered on an html form. An attacker can provide text that will do unexpected, possibly harmful, things.
Unfortunately the easiest way to write SQL queries in PHP is also the dangerous way:
mysql_query("UPDATE users SET age='$age' WHERE id = '$id'");
If the string $id is "foo' OR 'x'='x", the resulting query will be:
mysql_query("UPDATE users SET age=$age WHERE id = 'foo' OR 'x'='x'");
This will update age of every user, clearly not a good thing.
A safer way of doing this is:
if (get_magic_quotes_gpc()) {
$age = stripslashes($age);
}
mysql_query("UPDATE users SET age='".mysql_real_quote_string($age)."' WHERE id = '".mysql_real_quote_string($id)."'");
For more on sql injection read SQL Injection Attacks by Example