Categories Tags

PHP - The use of mysql_real_escape_string

I have recently seen posted numerous times that if you run the function 'mysql_real_escape_string' on any data, you are then automatically safe from SQL injection. Well, this isn't the case at all ... To start, let's look at what php's documentation about 'mysql_real_escape_string' says: php.net

Escapes special characters in the unescaped_string, taking into account the current character set of the connection so that it is safe to place it in a mysql_query(). If binary data is to be inserted, this function must be used. mysql_real_escape_string() calls MySQL's library function mysql_real_escape_string, which prepends backslashes to the following characters: \x00, \n, \r, \, ', " and \x1a. This function must always (with few exceptions) be used to make data safe before sending a query to MySQL.

So, not only does it force you to have the mysql connection (why is this really needed for just escaping a few characters?), it just adds a '\' before some of the characters which could break a query. This is because lots of people write queries as follows:


$query = "SELECT `user_id`, `username`, `startdate` FROM `users` WHERE `username` = '$username'";

However, if $username contains "blarg'; DROP TABLE `users`; --", then mysql_real_escape_string will change it to "blarg\'; DROP TABLE `users`; --" which will not break the query (so the users table will not be dropped). But if the attacker was smarter and used a different representation of it by using %39; (hexadecimal value for '), mysql_real_escape_string will not touch it, so it will go into your query and inconveniently drop your table. This small example shows the the use of 'mysql_real_escape_string' is ineffective in preventing against SQL injection. Instead of using 'mysql_real_escape_string' I would strongly suggest the use of database parameters (prepared statements) for all queries, or create a way which will convert from the %39; to their corresponding values (i.e. html special chars decode) just to make sure that characters you don't want to be in there don't sneak in.

Posted in php

Tags: