0

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?

1
  • I worked around this by sending the object elements to a function that replaces quotes with " before the stringify call and then decoding html entities in the php script. Would be interested to see if anyone has a more elegant solution.
    – Ammon B
    Feb 7, 2013 at 21:24

1 Answer 1

0

I was passing HTML code inside a string value in a JSON structure, and faced the same problem. However, i didn't had to replace the quotes, as JSON.stringify gives me a well formed string.

What i did was implementing a modified function from the one stated here: http://www.php.net/manual/en/security.magicquotes.disabling.php

<?php
if (get_magic_quotes_gpc()) {
    $process = array(&$_GET, &$_POST, &$_COOKIE, &$_REQUEST);
    while (list($key, $val) = each($process)) {
        foreach ($val as $k => $v) {
            unset($process[$key][$k]);
            if (is_array($v)) {
                $process[$key][stripslashes($k)] = $v;
                $process[] = &$process[$key][stripslashes($k)];
            } else {
                $process[$key][stripslashes($k)] = stripslashes($v);
            }
        }
    }
    unset($process);
}
?>

That way, it just applies stripslashes when magic quotes are enabled, and so far it seems not to break my JSON.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.