SQL Query Injection
A common problem in web development is guarding against
SQL injection attacks, this is were a attacker inserts
extra
SQL as a parameter.
So for instance:
mysql_query("SELECT * FROM Users WHERE Username = '" . $_POST['username'] . "'");
Could be attacked if
$_POST['username'] equalled:
' DELETE FROM Users WHERE 1=1 OR Username = '
Which would give a actual query of
SELECT * FROM Users WHERE Username = '' DELETE FROM Users WHERE 1=1 OR Username = ''
This would delete all the users in the user's table!
To get around this you can use a combination of
stripslashes and
mysql_real_escape_string or
mysql_escape_string.
mysql_escape_string also escapes a string however unlike the mysql_real_escape_string it doesn't take into account the current character set, however it also
doesn't require a database link.
$username = $_POST['username'];
if(get_magic_quotes_gpc())
{
$username = stripslashes($username);
}
mysql_query("SELECT * FROM Users WHERE Username = '" . mysql_real_escape_string($username, $database_link) . "');
// OR
mysql_query("SELECT * FROM Users WHERE Username = '" . mysql_real_escape_string($username) . "');
The
stripslashes function ensures that there are no slashes added automatically as this would counteract the
escaping made by the
mysql_real_escape_string function.
This function adds slashes to any quotes thereby stopping the attackers adding thier own code.
No comments have been provided.
Written by Dominic Skinner
Last Updated: 2011-10-25 16:00:38