PHP mysql_real_escape_string() -> stripslashes() leaving multiple slashes

Best Solution

In your php.ini file, odds are that the magic_quotes_gpc directive is set to on. This should be disabled for security reasons. If you don’t have access to the php.ini file (eg. on a shared host), you can always accomplish the same using an .htaccess directive (assuming this is an apache server).

In your php.ini

magic_quotes_gpc Off

In an .htaccess file:

php_flag magic_quotes_gpc Off

Why is this happening?

The reason this is happening is due to the following course of logic.

  1. A string that needs escaping is sent to the server.
    • This is my string. It's awesome.
  2. Magic Quotes escapes the apostrophe before it gets to your code.
    • This is my string. It\'s awesome
  3. mysql_real_escape_string now has two characters to escape, the backslash \\ as well as the apostrophe \'.
    • This is my string. It\\\'s awesome
  4. This new super-escaped string is stored in the database.
  5. When the string is retrieved from the database, it get’s passed to stripslashes. This removes the two escapes added in step 3, but since one of the backslashes has been escaped stripslashes thinks it belongs.
    • This is my string. It\'s awesome

This problem can really get out of hand when you re-submit these strings to the database, as each time the number of backslashes multiplies.

Alternative Solution

A quick-and easy alternative would be to simply remove the slashes added by magic_quotes before passing the string to mysql_real_escape_string.

$str = stripslashes($_POST['str']);
$str = mysql_real_escape_string($str);

Leave a Comment