I’m wondering if there are ways to perform SQL attacks even when the mysql_real_escape_string() function is being used for sanitization.
Let me show you an example of what I’m working with:
$username = mysql_real_escape_string(GetUserInput('username'));
$pass = mysql_real_escape_string(GetUserInput('pass'));
$query = "SELECT * FROM users WHERE username='$username' AND pass='$pass'";
Several developers have warned me that this approach might still have security flaws and could be vulnerable to attacks, but I can’t figure out how someone could exploit it.
The typical attack patterns like:
test' OR 1=1 --
get blocked by the escape function.
Are there any known attack methods that could still work against this type of PHP code setup?
Yes, mysql_real_escape_string() can definitely be bypassed. Character set attacks are one of the most well-known methods; if you’re using character sets like GBK or Big5, attackers can create multibyte sequences that break the escaping. Numeric contexts also pose a significant weakness. For instance, if your application expects an integer but still treats it as a string in the query, an attacker could inject SQL without needing quotes. Moreover, the old mysql extension is inherently risky due to its lack of modern security features. The key issue is that mysql_real_escape_string() only blocks certain dangerous characters and cannot cover every potential injection method. It’s advisable to use prepared statements with parameter binding as they effectively separate your SQL code from user input.
Interesting question! What about second-order injections tho? Like when you escape data going into the database, but then use it unsafely later? Also - are you checking that your connection charset matches your app charset? A mismatch there could cause problems too.
true! also, always try to use prepared statements or parameterized queries. that way, you avoid many issues. relying only on mysql_real_escape_string isn’t enough anymore, especially with complex queries.