0

I post data to a PHP file. The POST and GET data is empty, but php://input perfectly shows the posted data.

How is this possible? And what can I do to check / fix this?

This is my code:

    const myJSON = JSON.stringify(data); 
    let result   = myJSON.replace("[{","{");
    result       = result.replace("}]","}");
    result       = result.replace(/},{/g,",");

    var user     = '{{ Auth::user()->name }}';
    var l        = document.getElementById("languages");
    var langcode = l.value;
    var params   = 'user='+user+'&lang='+langcode+'&data='+result;
    var url      = "/public/test.php";
    
    var xhr = new XMLHttpRequest();
    xhr.open("POST", url, true);
    xhr.setRequestHeader('Content-type', 'application/json');
    xhr.send(params);
MikeMynis
  • 19
  • 3

2 Answers2

0

Ah, solution:

Change:

xhr.setRequestHeader('Content-type', 'application/json');

into

xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded; charset=UTF-8');
MikeMynis
  • 19
  • 3
0

I know you have found a solution to your question, but I'd like to point out that you are doing some very dangerous things here, that in the best case will corrupt your data and in the worst case make your site vulnerable to script injection.

  1. If you are not sending JSON, then don't use JSON.stringify and then manipulate the string like that. If the data contains those strings you are replacing, then that will corrupt it, and if that data is user input allow script injection.

  2. I assume {{ Auth::user()->name }} is some server-side code. If the user name contains a quote or anything that is not a valid JavaScript string, this will break the JavaScript and possibly allow script injection by a malicious user. Also: Why are you sending the user name back in the request? The server already knows the username. This seems that it would allow a malicious use to read or write data belonging to another user, if the request is manipulated.

  3. Don't build query strings like that yourself without escaping the data. This break your script if it contains characters that aren't allowed in URLs, which it does: { and } are not valid charcters in URLs. Use for example use the URLSearchParams API to build a properly escaped query string.

  4. Finally, it not really security related, but the newer Fetch API is easier to use and more powerful than the older XMLHttpRequest.

RoToRa
  • 37,635
  • 12
  • 69
  • 105