Rivka, probably the easiest example of an sql injection is this:
You have a login form, has a username field, a password field, and a submit button. This form submits to your form handler page, which queries your mysql database. You have written your code so that if the query returns true, then the user is given access. eg:
$sql = "SELECT id FROM users WHERE username='".$_POST['username']."' AND password='".$_POST['password']."'";
$result = mysql_query($sql);
if($result) {
// Give user access
}
Recognize that? It's pretty common. Let's look at this situation.
The malicious user in question puts "HaXx0r" as his/her username. (Note, this is not a valid username).
In the password field the user then puts this:
foo' OR 1=1--
The query that is then formed from this is:
SELECT id FROM users WHERE username='HaXx0r' AND password='foo' OR 1=1
(the -- ignores the rest of the query, avoiding the final ' ).
Think about this query. It will ALWAYS return a result, because 1 is always = 1, and as such the malicious user now has access using an invalid username and password.
That's an sql injection 🙂
Now, how to avoid this!
PHP has a whole bunch of functions that'll stop this for you, but it sucks to remember to do it on every variable that you're going to put into a database. As such, I've created a nice little function that will clean it up. I'm sure there's a hundred thousand or so of them out there, but this one works for me!
function clean_input($needle) {
if(is_array($needle)) {
$haystack = array();
foreach($needle as $k=>$v) {
$haystack[$k] = (!get_magic_quotes_gpc()) ? mysql_escape_string($v) : $v;
$haystack[$k] = trim($haystack[$k]);
}
} else {
$haystack = (!get_magic_quotes_gpc()) ? mysql_escape_string($needle) : $needle;
$haystack = trim($haystack);
}
return $haystack;
}
Run your input through that, eg:
$input = clean_input($_POST);
and it will clean it up for you, then just refer to it using $input.
This would make the above sql injection useless, because it would look like this:
SELECT id FROM users WHERE username='HaXx0r' AND password='foo\' OR 1=1--'
(Notice the ' after foo is escaped).
Hope that helps,
Matt