However, even more annoying than this was that the code worked perfectly fine on the live server but not a damn did it want to run on my local machine!
So I scratched around using good old FireBug and after a little investigation and a whole lot of printing out of values, I noticed that the result of my stringified JSON data held in the POST variable was in fact looking different across the live and localhost server.
Well for a start there were delimited quotation marks appearing on the local machine instead of the plain old quotation marks showing up on the live server.
Now by delimited I mean the quotes were all being prefixed by slashes, meaning that a simple stripslashes on the JSON data would work perfectly well and solve my problem – but of course as we all can think for ourselves, that isn’t exactly the root of the problem now is it?
So what is adding in all these unwanted slashes then?
Well the answer of course is PHP’s magic_quotes_gpc ini setting. For those of you who don’t know, essentially this setting came in existence to help programmers who routinely forgot to delimit their strings when inputting them into databases, and also as a sort of automatic defense mechanism against simple SQL injection attacks. By turning magic quotes on, the server automatically delimits all incoming quotes held in the HTTP Request data (i.e. GET, POST, COOKIES) if they aren’t already delimited, meaning that in essence, it is possible for lazy programmers to get away with murder.
Of course, this has since been viewed as a bad idea and is deprecated from PHP 5.3.0.
Anyway, for some or other very strange reason, XAMPP has seen it fit to leave magic_quotes_gpc on in its default installation package and this was what was causing all the hassles on my local development environment.
Thankfully turning it off is as simple as walking to the php.ini file and changing the line magic_quotes_gpc = On to magic_quotes_gpc = Off.
However, if say the situation was reversed and the problem was sitting on a server whose ini file you can’t manipulate (and remember, magic quotes can’t be manipulated at runtime in the usual set ini fashion), here is a solution for you that actually works rather well:
$value = is_array($value) ? array_map("stripslashes_deep", $value) : stripslashes($value);
$_POST = array_map("stripslashes_deep", $_POST);
$_GET = array_map("stripslashes_deep", $_GET);
$_COOKIE = array_map("stripslashes_deep", $_COOKIE);
$_REQUEST = array_map("stripslashes_deep", $_REQUEST);
As you can see above, we first check to see if magic quotes are indeed turned on. If yes, run a recursive stripslashes function against each HTTP request data variable we can think of and presto, problem solved!