String JSON-encoded with ExtJS can't be decoded with json_decode in PHP

10,512

When you get your POST data, run it through stripslashes.

$grid_data = json_decode ( stripslashes ( $_POST['grid_data'] ), true);
Share:
10,512
xlttj
Author by

xlttj

Full stack web developer with 20+ years experience in macOS, Linux, MySQL, Apache, nginx, PHP, JavaScript, HTML, CSS, Atlassian and a whole lot of other buzzwords

Updated on June 04, 2022

Comments

  • xlttj
    xlttj almost 2 years

    I'd like to store data from an input field to a database. However, when the user decides to enter some backslashes or quotes, i'm screwed.

    I'm using the following code on the client side. The value of mystring is in fact read from an input field.

    mydata = Ext.encode({
        mystring : "foo '\' bar ' \0x00\""
    });
    
    Ext.Ajax.request({
      url: '/test.php',
      params: { data: mydata }
    });
    

    On the server, print_r($_POST) gives me

    array(
      ['data'] => '{"mystring":"foo '' bar ' \u0000x00\""}'
    )
    

    So, I lost the backslash after foo, and the \0x became \u00, and

    var_dump(json_decode($_POST['data'])
    

    fails and returns

    NULL
    

    In an other case, when the user uses quotes, I get

    mydata = Ext.encode({
        {"mystring":"foo '\"' bar '"}
    });
    

    and I end up on the PHP side with $_POST

    array(
      ['data'] => '{"mystring":"foo '"' bar '"}'
    )
    

    which too is no valid input for json_decode().

    I want the user input literally. I'd like to let my database wrapper take care of the escaping stuff before the INSERT command, but how can I send arbitrary strings, potentially containing any amount of slashes, backslashes, double and single quotes safely to my PHP script and json_decode it successfully?

    I already thought about base64 encoding, but that is not very much an option.

    See http://dev.sencha.com/deploy/dev/docs/?class=Ext.util.JSON for documentation.


    Edit:

    The data is read from the store of an Ext.grid.EditorGridPanel myGrid. The whole script has about 2.500 LoC, so I only post an excerpt here. I also changed some variable names to make the whole stuff more readable.

    var modRec = myGrid.getStore().getModifiedRecords();
    var data = new Array();
    var len = modRec.length - 1;
    for (f = len; f > -1; --f) {
        var a = {};
        var changes = modRec[f].getChanges();
        for (var name in changes) {
            if ('function' == typeof changes[name]) {
                continue;
            }
            a[name] = changes[name];
        }
        data.push(a);
    }
    
    Ext.Ajax.request({
        url: '/test.php',
        params: { Ext.encode(data) }
    });
    

    The result is the same as above. When a user enters a double quote into the editor field of the grid cell editor, which is an Ext.form.TextField, the string is not encoded and decoded correctly.