This question already has an answer here:
So PHP is having a lot of trouble dealing with ' characters in strings recently in one of my projects, and I think the main reason behind this is for some crazy reason it's doubling the \ character. I've checked, and magic quotes are off (so this is not the culprit). Anyways, given the following code:
26 $comments = $_POST['comments'];
27 error_log("comments: '$comments'");
28 $comments = mysql_real_escape_string($_POST['comments']);
29 error_log("escaped comments: '$comments'");
I'm seeing the following in the error log:
[Sun Oct 19 14:18:53 2014] [error] [client XXXX] comments: 'something elsewearwerawer's woeimrowiamrw', referer: ...
[Sun Oct 19 14:18:53 2014] [error] [client XXXX] comments escaped: 'something elsewearwerawer\\'s woeimrowiamrw', referer: ...
Even worse, I still see the same behavior after swapping things over to PDO:
error_log("quoted: '" . $db_pdo->quote($comments) . "'");
Even when I do something simple like:
error_log('\\');
or
error_log("\\");
The error log shows:
[Sun Oct 19 17:44:57 2014] [error] [client XXXX] \\, referer: ...
Any idea what is going on here? I'm worried because it looks like this means mysql_real_escape_string (or PDO) is not correctly escaping single quotes in strings, which could lead to a SQL injection. Whenever I try and update/insert with a string with a ' in it, even after calling mysql_real_escape_string or by using quote (or bindParam with a string), it doesn't insert anything after the '
SOLVED: After digging deeper it was actually inserting things into the database correctly, the error was happening on the other end of things when the webpage was pulling from the database and not dealing with the ' correctly, so it was getting cut off in the html.
</div>
You need to turn off magic_quotes_gpc
parameter in your php.ini config.
http://php.net/manual/en/security.magicquotes.disabling.php
As a workaround you can remove the slashes it's adding automatically, using stripslashes()
, by doing this:
$comments = mysql_real_escape_string( stripslashes( $_POST['comments'] ) );
or this (using PDO)
$comments = $db_pdo->quote( stripslashes( $comments ) );
Your escaping actually looks normal, it only looks like there is double escaping going on because Apache escapes backslashes in its log as described here. Thus, when you see \\'
in the log, it is actually just \'
in the string you have in PHP. If you want to test this, echo
the escaped string instead of using error_log
.