Imagine a standard login box, written in PHP
and checking users in a MySQL database
. A normal user/password check would look like:
* FROM users WHERE username='$username' AND password='$password');
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:
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:
if($link != 0)
Use it as you like, and feel free to improve upon it or offer better suggestions.