Preventing MySQL Injection attacks with PHP
Using PHP in preventing MySQL injection attacks on your site
Published Jul 6, 2005 by lobo235The first step in preventing MySQL injection attacks on your website is to understand what they are. An injection attack occurs when a visitor to your site types something into a form input with the purpose of changing the outcome of your MySQL query. For example, at a login screen someone might use this type of attack to gain access to a secure area of the website. If your query to check the username and password entered by the user was this:
"SELECT * FROM users WHERE username = '".$_POST['username']."' AND password = '".$_POST['password']."'" Someone could login by using any username and for the password they would type ' OR ''='' which would be placed into your MySQL query changing it to be:
"SELECT * FROM users WHERE username = 'anyuser' AND password = '' OR ''=''" As you can see, MySQL injection attacks can be pretty serious depending on the information the person has access to once they are logged in. It is very important for you to secure your site against injection attacks. Luckily, PHP can aid you in preventing injection attacks.
MySQL will then return all the rows in the table and then, depending on your script's logic, you will probably log them in because there was a match. Now, in most cases, people have magic_quotes_gpc turned on (it's the PHP default) which will add backslashes to escape all ' (single-quote), " (double quote), (backslash) and NULL characters. This is not foolproof though because there are other characters that should be escaped to be safe. There is a function built into PHP that will escape all MySQL characters that could be used to inject additional SQL into your queries. The function is mysql_real_escape_string().
You need to be careful when using this function though because if you already have magic_quotes_gpc turned on and then you use mysql_real_escape_string() you will end up escaping things that have already been escaped. The following function found on the PHP webpage will use mysql_real_escape_string() to correctly escape data inserted into your queries regardless of the magic_quotes_gpc setting.
<?php
// Quote variable to make safe
function quote_smart($value)
{
// Stripslashes
if (get_magic_quotes_gpc()) {
$value = stripslashes($value);
}
// Quote if not integer
if (!is_numeric($value)) {
$value = "'" . mysql_real_escape_string($value) . "'";
}
return $value;
}
?>
It's important to note that the quote_smart() function will automatically add single quotes to strings passed into it so you do not have to put them in yourself. If you have any questions or comments concerning this article, please let us know.
4 comments for this article.
add this article to del.icio.us!
Javascript DOM insertAfter function
Floating DIVs for Photo Gallery
Unobtrusive Javascript made easy
