Forum Moderators: coopster

Message Too Old, No Replies

FAQ: Why addslashes in a databse?

An example of why to addslashes in MySQL

         

FiRe

1:51 pm on Jul 5, 2006 (gmt 0)

10+ Year Member



It is important to addslashes to any input into your database, to prevent what is known as "SQL injections". Consider the following SQL statement:

SELECT * FROM users WHERE username='$user' AND password='$pass'

If $user = "admin" and $pass = "blah" the SQL statement would look like this:

SELECT * FROM users WHERE username='admin' AND password='blah'

Thats all very nice, but remember the user inputs the username and password. Conside this code:

$user = $_POST['user'];
$pass = $_POST['pass'];

$query = "SELECT * FROM users WHERE username='$user' AND password='$pass'";
$result = mysql_query($query);

if (mysql_num_rows($result) == 1) {
echo "You now have admin access!";
}

Now if the user enters "admin" and password = "' OR 'a'='b" look what the code looks like now:

$user = "admin"
$pass = "' OR 'a'='b";

$query = "SELECT * FROM users WHERE username='$user' AND password='$pass'";
$result = mysql_query($query);

if (mysql_num_rows($result) == 1) {
echo "You now have admin access!";
}

If you were to echo the $query you would see:

$query = "SELECT * FROM users WHERE username='admin' AND password='' OR 'a'='b'";

And that would be a valid statement, thus giving us admin access!

Now if you replace the $user and $pass with this:

$user = addslashes($_POST['user']);
$pass = addslashes($_POST['pass']);

Our SQL statement would look like this:

$query = "SELECT * FROM users WHERE username='admin' AND password='\' OR \'a\'=\'b'";

And it would not be valid!

Remember you only need to addslashes if magic_quotes are disabled.

Enjoy :-)

Sekka

2:26 pm on Jul 5, 2006 (gmt 0)

10+ Year Member



addslashes () is good, but personally I prefer using mysql_escape_string ().

But either way, a very valid and important point.

eelixduppy

2:28 pm on Jul 5, 2006 (gmt 0)



Query variables should ALWAYS (with little exception) be escaped with mysql_real_escape_string [us3.php.net] or mysql_escape_string [us3.php.net] and NOT addslashes [us3.php.net]. If it is the case that magic_quotes are enabled, the variable should be stripped of its slashes(stripslashes [us3.php.net]), and then mysql_real_escape_string should be applied.