I have a PHP script that accepts posts from other servers in JSON format. Sometimes the external server has magic quotes enabled, so I pass it through stripslashes() just to be safe. However, I run into problems when the data being posted also has a quote character. This also gets escaped by the remote server and then stripslashes on my server incorrectly strips that as well, breaking the JSON.
For example, I can pass and accept the following JSON easily:
stuff = {"items":["item1","item2"],
"urls":["url1","url2"],
"pics":["pic1","pic2"]};
However, this will break:
stuff = {"items":["item_including_quotes1","item_including_quotes2"],
"urls":["url1","url2"],
"pics":["pic1","pic2"]};
I do not have control over the remote array values and they can contain single and double quotes. I do have control over how they are prepared for sending. Currently the javascript looks like this:
encodeURIComponent(JSON.stringify(stuff));
and the PHP looks like this:
json_decode(stripslashes(urldecode($_POST["stuff"])));
This data is posted with javascript JSON.stringify and encodeuricompnent and processed with PHP json_decode and urldecode.
I considered a regex to remove backslashes only when they appear between brackets [], but this seems kludgy. Is there a more elegant solution for removing only certain slashes?