I've heard people say (in relation to C#/SQL Server, but also in relation to PHP/MySql): Don't escape strings manually - use stored procedures instead.
Ok, I can accept this suggestion, but why? Many say (including on SO) mysql_real_escape_string()
is quite enough, mysql_real_escape_string()
is good, mysql_real_escape_string()
is the first way of protection.
Why? Is there a case where mysql_real_escape_string()
can fail? At least one... I don't need many :)
PHP provides mysql_real_escape_string() to escape special characters in a string before sending a query to MySQL. This function was adopted by many to escape single quotes in strings and by the same occasion prevent SQL injection attacks.
The real_escape_string() / mysqli_real_escape_string() function escapes special characters in a string for use in an SQL query, taking into account the current character set of the connection.
This extension was deprecated in PHP 5.5. 0, and it was removed in PHP 7.0.
The only sure way to prevent SQL Injection attacks is input validation and parametrized queries including prepared statements. The application code should never use the input directly. The developer must sanitize all input, not only web form inputs such as login forms.
When mysql_real_escape_string FAIL:
$sql = "SELECT * FROM users WHERE id=" + mysql_real_escape_string($_GET['id']);
If $_GET['user_id']
is set to 1 OR 1=1, there are no special chars and it's not filtered.
The result: All rows are returned.
It gets worse. How about this... what if $_GET['user_id']
is set to 1 OR is_admin = 1?
The function is only designed to be used when inside single quotes.
There are two things that can go wrong with mysql_real_escape_string
:
SET NAMES
instead of mysql_set_charset
as is proper, it can still leave you vulnerableUpdate:
SET NAMES
!)Just for info:
mysql_real_escape_string()
does not escape %
and _
. These are wildcards in MySQL if combined with LIKE, GRANT, or REVOKE
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With