0

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.

tdes
  • 21
  • 4

2 Answers2

1

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.

Austin
  • 2,982
  • 2
  • 28
  • 36
0

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 ) );

Patrick Moore
  • 13,251
  • 5
  • 38
  • 63
  • magic_quotes_gpc is off, but i found the solution. It was actually getting into the database correctly, but when being passed back to the javascript in the webpage was where it was getting cut off. – tdes Oct 19 '14 at 23:16