I'm having issues escaping/stripping strings with PHP/MySQL - there always seems to be redundant slashes.
Let's take the following string as an example:
<span style="text-decoration:underline;">underline</span>
When adding a string to the database, I'm escaping it with mysql_real_escape_string()
and the following gets stored in the database (EDIT: checked this by querying the database directly with mysql app):
<span style=\\\"text-decoration:underline;\\\">underline</span>
When reading back out of the database, I'm passing the string through stripslashes()
and the following is returned:
<span style=\"text-decoration:underline;\">underline</span>
Since the quotes are still escaped, it breaks the html and the text is not underlined.
mysql_real_escape_string()
adding three slashes, and stripslashes()
removing two slashes? I would expect them both to add/remove one slash.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
The reason this is happening is due to the following course of logic.
This is my string. It's awesome.
This is my string. It\'s awesome
mysql_real_escape_string
now has two characters to escape, the backslash \\
as well as the apostrophe \'
.
This is my string. It\\\'s awesome
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.
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);