display | more...
Imagine a standard login box, written in PHP and checking users in a MySQL database. A normal user/password check would look like:

$username=$_POST['username']
$password=$_POST['password']
$res=mysql_query("SELECT * FROM users WHERE username='$username' AND password='$password');
if(mysql_num_rows($res)==1)
echo "the user is logged in successfully";

A major problem exists in this, however.
Suppose a malicious hax0r filled in for password, "blah' OR 1". The query would look like this:

SELECT * FROM users WHERE username='teh_hax0r' AND password='blah' OR 1

This expression always evaluates to true because of the OR 1. This is a major problem. The creators of MySQL and PHP have attempted to circumvent this with settings like magic_quotes_gpc, which automatically escapes potentially malicious database data, but a bad admin can always screw this up and make your code insecure. However, if you blindly mysql_escape_string a string, it could be escaped twice by magic_quotes_gpc and make your code useless. A solution would be to check if the option is set in PHP settings, and adjust accordingly. Another excellent feature of PHP is that mysql_real_escape_string() can check the default character set on a given database connection and adjust for it. So a nifty database input string securer i use is as follows:

function sekureStr($str,$link=0)
{
if((bool)ini_get("magic_quotes_gpc"))
{
return $str;
}
else
{
if($link != 0)
return mysql_real_escape_string($str,$link);
else
return mysql_escape_string($str);
}
}

Use it as you like, and feel free to improve upon it or offer better suggestions.

Log in or register to write something here or to contact authors.