The horrible magic quotes in PHP

A little more than a year ago, I had some problems when AJAX:ing data to a PHP page. In order to be able to unpack the data, I had to use the stripslashes method, which did not seem all that intuitive. However, since it worked, I let it remain without any further considerations.

Then, about a month ago, I published a new web site that I had developed for a friend. For that page, when I posted HTML content via AJAX, all line feeds turned into u000a strings. The problem only occured on his domain, and not on mine, and looks like this:

Magic quotes in action - all line breaks are turned into u000a

Magic quotes in action – all line breaks are turned into u000a

So then, yesterday, the problem finally appeared at my domain as well. I did not understand this at all, until I chatted with a friend of mine, who just brainstormed and came up with the solution.

Magic quotes.

Ok, the purpose of this feature was to protect pages from injections, but it did not work all that well, so the feature is now deprecated. What it does is that is wraps everything in neat little escape slashes, which is why I had to use stripslashes.

However, if magic quotes are disabled, stripping the slashes will instead destroy the escaped line break.

So, I now disable magic quotes for all pages, using this in an .htaccess file:

   php_flag magic_quotes_gpc off

Thanks Mattias – it works like a charm!

Advertisements