PHP and SQL injection

Ok, being someone who likes php, i get annoyed at the many sites trying to teach people the language who have example login scripts that use something like:

$result=mysql_query("select * from users where Username=$username and Password=$password");
if (mysql_num_rows($result) < 1)
    blah blah blah

Whats wrong with that you ask? Well imagine what would happen if someone were to use the username '' or 1=1 #, what that would do is return the entire table because 1 is always equal to 1 and the # will cause mysql ignore the rest of the query, and thus executing this instead select * from users where Username='' or 1=1
What you should be using is something like this.. (if you dont already)

$username = mysql_real_escape_string($username);
$result = mysql_query("select Password from users where Username = '$username' Limit 1");
$result = mysql_fetch_assoc($result);
if ($result['Password'] === $password)
    blah blah blah

Which is far more secure, the first line escapes all single quotes'n'stuff, the actual query fetches one row only and the use of === means that it will also evaluate the type of data, whereas == may evaluate to true if $password is set to boolean true. If you cant be bothered to write the whole mysql_real_es.... you can use this:

function sql_escape($string)
{
    return mysql_real_escape_string($string);
}

Thats all for now folks.

Bookmark the permalink.

Leave a Reply

Your email address will not be published.