Introduction
When working with technologies such MySQL, developers should aim to correctly sanitize input, as such systems can be easily exploited. This guide is not thorough and I expect the reader to have prior knowledge of both PHP and MySQL.
Background
Databases store information in tables. In turn, queries are used to obtain, update and insert information, an in such tables for given criteria. Queries are made up of keywords (INSERT
, UPDATE
, SELECT
), table names and other values (PHP variables for example). Together, these values build a string (known as an SQL statement) which is then executed using a function such as mysqli_query()
. The problem is, when one wishes to use raw user input (say a username or password) from a form, there is a chance the input may contain SQL statements. In turn, the statements can execute causing unexpected results such as the unauthorised deletion of tables, or the unauthorised insertion of extra records.
What can be done to stop this problem? MySQL injection is an old and recognised exploit. Functions were created to correctly sanitize user input, removing the chances of successful SQL injection. In particular, the function mysql_real_escape_string()
should be used along with stripslashes()
if magic_quotes_gpc
is on.
Using these functions is really simple. The first function adds back slashes to a few special characters (if they exist in the user input) in order to escape them. This function has two parameters: the first is an un-escaped string obtained from the user (usually from a form field) and the second is an optional link identifier. The link identifier may or may not be optional depending on the solution. When you use mysql_connect
, the resulting string is used for the second argument in the mysql_real_escape_string()
function. On a side note, if you are using mysqli_connect
to connect to your database, you may have to use mysql_connect
instead.
The second function, stripslashes()
is used to remove quotes from a quoted string. The function has a single parameter, the string which is to be sanitized. This function is only required if magic_quotes_gpc
is on. This can be found by using the phpinfo()
function.
Putting It All Together
Finally, we can build a function to remove SQL injection from raw strings, which can be seen below. Obviously your connection string will differ for your database/server.
function Remove_SQLi($str)
{
$connection_string = mysql_connect('server', 'database_user','user_password');
if(get_magic_quotes_gpc())
{
return mysql_real_escape_string(stripslashes($str), $connection_string);
}
else
return mysql_real_escape_string($str, $connection_string);
}
This should stop most attacks, but it still may be susceptible to blind-SQL injection! If you are interested in other exploits, try looking up XSS (cross-site scripting).
Related Reading
This article was taken from my personal website, more articles and my blog can be found there.
History
- 19th October, 2009: Initial post