Is there an SQL injection possibility even when using mysql_real_escape_string() function?

Consider this sample situation. SQL is constructed in PHP like this:

$login = mysql_real_escape_string(GetFromPost('login'));
$password = mysql_real_escape_string(GetFromPost('password'));

$sql = "SELECT * FROM table WHERE login='$login' AND password='$password'";

I have heard numerous people say to me that a code like that is still dangerous and possible to hack even with mysql_real_escape_string() function used. But I cannot think of any possible exploit?

Classic injections like this:

aaa' OR 1=1 --

do not work.

Do you know of any possible injection that would get through the PHP code above?


Usually it's better to do the password validation in the PHP code so you can display a more verbose error (invalid user / invalid password)

Written by ThiefMaster

@ThiefMaster I know, the above is just a simple example to get my point across.

Written by Richard Knop

Always use prepared statements. The security provision, performance benefits of statement re-use, standardised coding, and library maintainance always (in my opinion) out-weigh any other alternative 'short-cut' method.

Written by Dems

@ThiefMaster - I prefer not to give verbose errors like invalid user / invalid password... it tells brute force merchants that they have a valid user ID, and it's just the password they need to guess

Written by Mark Baker

It's horrible from an usability point of view though. Sometimes you couldn't use your main nickname/username/email-address and forget this after some time or the site deleted your account for inactivity. Then it's extremely annoying if you continue trying passwords and maybe even get your IP blocked even though it's just your username that is invalid.

Written by ThiefMaster

possible duplicate of Is mysql_real_escape_string() broken?

Written by Gordon

Accepted Answer

Concider the following query:

$iId = mysql_real_escape_string("1; DROP table");    
$sSql = "SELECT * FROM table WHERE id = $iId";

mysql_real_escape_string will not protect you against this. The fact that you use single quotes '' around your variables inside your query is what protects you against this. The following is also an option:

$iId = (int)mysql_real_escape_string("1; DROP table");
$sSql = "SELECT * FROM table WHERE id = $iId";
This page was build to provide you fast access to the question and the direct accepted answer.
The content is written by members of the community.
It is licensed under cc-wiki