Asked  7 Months ago    Answers:  5   Viewed   31 times

file_get_contents("php://input") or $HTTP_RAW_POST_DATA - which one is better to get the body of JSON request?

And which request type (GET or POST) should I use to send JSON data when using client side XmlHTTPRequest?

My question was inspired from this answer: How to post JSON to PHP with curl

Quote from that answer:

From a protocol perspective file_get_contents("php://input") is actually more correct, since you're not really processing http multipart form data anyway.

 Answers

69

Actually php://input allows you to read raw POST data.

It is a less memory intensive alternative to $HTTP_RAW_POST_DATA and does not need any special php.ini directives.

php://input is not available with enctype="multipart/form-data".

Reference: http://php.net/manual/en/wrappers.php.php

Wednesday, March 31, 2021
 
EnTee
answered 7 Months ago
53

The problem is in your Content-Type. If you use application/json the PHP won't parse the post data into $_POST variable. You have to send them as form data to have PHP parse it.

See this question for more info Send POST data using XMLHttpRequest

Alternatively you can use file_get_contents("php://input") to get the raw body of HTTP request and parse the json with json_decode.

Example with file_get_contents and json_decode

PHP Code:

$in = file_get_contents('php://input');
$decoded = json_decode($in, true);
$data = new stdClass();
$data->msg = 'PHP is working';
$data->user = $decoded['user'];
$data->pass = $decoded['pass'];
echo json_encode($data);

JS Code:

var data = { 'user': 'myUser', 'pass': 'myPass' };

    var xhr = new XMLHttpRequest();
    xhr.open('POST', 'myUrl', true);
    xhr.setRequestHeader("Content-Type", "application/json; charset=UTF-8");
    xhr.onreadystatechange = function () {
        if (xhr.readyState === 4 && xhr.status === 200) {
            var res = JSON.parse(xhr.response);
            console.log(res);
        }
    };

    xhr.send(JSON.stringify(data));
    return false;

Please notice that you need to JSON.stringify the data object before passing it as argument to send() method. Otherwise the data are not send correctly.

Wednesday, March 31, 2021
 
Terry
answered 7 Months ago
50

Instead of XMLHttpRequest, you can use the new Fetch API. XMLHttpRequest has been deprecated and is not available in the service worker scope.

There's an example of exactly what you want to achieve in this ServiceWorker Cookbook recipe.

Wednesday, March 31, 2021
 
Hugo
answered 7 Months ago
94

Conditionals are slower than plain arithmetic operations, but much, much faster than something as silly as calculating the square root.

Rules of thumb from my assembly days:

  • Integer or bitwise op: 1 cycle
  • Floating-point add/sub/mul: 4 cycles
  • Floating-point div: ~30 cycles
  • Floating-point exponentiation: ~200 cycles
  • Floating-point sqrt: ~60 cycles depending on implementation
  • Conditional branch: avg. 10 cycles, better if well-predicted, much worse if mispredicted
Sunday, July 11, 2021
 
medhybrid
answered 3 Months ago
53

Bit late, but I wanted to share my opinion on this.

I faced this problem recently when I found a Java project with both libraries and they were used at the same time.

I think that org.json is easier to read and to use, for 2 main reasons (for my needs):

  1. JsonObject is immutable. You can't add new key/value pairs to an already existing JsonObject (reference here: javax.json: Add new JsonNumber to existing JsonObject)

  2. It takes a few lines to pretty print a JsonObject or JsonArray, while it only takes 1 line to do it with JSONObject or JSONArray. Example:

    StringWriter sw = new StringWriter();
    Map<String, Object> properties = new HashMap<>();
    properties.put(JsonGenerator.PRETTY_PRINTING, true);
    
    JsonWriterFactory writerFactory = Json.createWriterFactory(properties);
    JsonWriter jsonWriter = writerFactory.createWriter(sw);
    
    jsonWriter.writeObject(jsonObject); //JsonObject created before
    jsonWriter.close();
    String prettyPrintedJSON = sw.toString();
    

That is the code I use to get an indented JSON to write to a file. And with org.json I only need jsonObject.toString(4).

Another difference is the constructors. You will need a JsonObjectBuilder to create a JSON with javax.json. One step more that can be avoided.

I'm sure there are more differences (not sure if it's possible to create a JsonObject from a String) but these are my thoughts.

Monday, August 9, 2021
 
newbStudent
answered 2 Months ago
Only authorized users can answer the question. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :