Why file_get_contents('php://input') Returns a String for JSON Messages
When working with PHP, it is common to assume that file_get_contents('php://input') will behave intuitively. You might expect it to parse incoming data or at least return the raw body in a way that immediately suggests how to handle it. However, developers frequently run into the scenario where they retrieve a JSON payload, attempt to decode it with json_decode(), and encounter a fatal error: "Trying to get property of non-object."
This happens because file_get_contents('php://input') strictly returns a string containing the raw request body. It does not automatically parse the content based on the Content-Type header, nor does it validate the JSON structure before returning it. In the specific case described, the variable $json holds a string representation of the data, but when that string is echoed directly, it appears URL-encoded or modified in unexpected ways, leading to confusion about whether the data was received correctly.
The Root Cause: Raw Input Streams
The function php://input refers to a PHP stream wrapper that reads the raw body of the request. This mechanism is designed for scenarios like streaming uploads or processing binary data where the server needs to handle the input byte-by-byte without buffering the entire response into memory immediately.
When you execute file_get_contents('php://input'), PHP reads every byte sent by the client until the Content-Length header indicates the end of the stream. The result is always a string. If your frontend sends:
{
"S3URL": "http://url.com"
}
PHP receives exactly that text. However, if you observe output like S3URL=http%3A%2F%2Furl.com, it suggests one of two things is happening: either the raw string is being inspected incorrectly in your debugging environment, or there is middleware involved (such as a reverse proxy) that is modifying the body content before it reaches your PHP script.
The error Trying to get property of non-object occurs because you are trying to access $obj->{'S3URL'} on a variable that failed to decode. The json_decode() function returns null if the provided string is not valid JSON, or if the decoding fails due to syntax errors. In this case, the input string likely contains characters that look like JSON but are malformed relative to what json_decode() expects, or the variable actually holds a URL-encoded string rather than the raw JSON object.
Handling the Input Correctly
To resolve this issue, you must ensure that the raw input is treated as a string before decoding. The standard approach involves checking the result of json_decode() for validity. If it returns null, you should handle the error gracefully rather than assuming the data structure exists.
Here is a robust pattern for handling incoming JSON data:
$json = file_get_contents('php://input');
if ($json === false) {
// Handle read failure (e.g., empty body or stream error)
http_response_code(400);
exit('Could not read request body.');
}
$obj = json_decode($json, true);
if ($obj === null && json_last_error() !== JSON_ERROR_NONE) {
// Handle invalid JSON syntax
http_response_code(400);
echo 'Invalid JSON payload received.';
exit(json_last_error_msg());
}
// Now safe to access properties
if (isset($obj['S3URL'])) {
echo $obj['S3URL'];
} else {
// Handle missing key
http_response_code(400);
echo 'Missing required S3URL parameter.';
}
Note the use of json_last_error() and JSON_ERROR_NONE. Relying solely on a boolean check for null is insufficient because json_decode() returns false (which becomes null after conversion in some contexts) even when the input string is empty. Always verify the error code to distinguish between an empty payload and malformed JSON.
The Role of Content-Type Headers
While PHP does not automatically parse incoming data based on headers, checking the Content-Type header can help validate expectations. A well-formed request should include Content-Type: application/json. If your server is receiving requests where this header is missing or set incorrectly (e.g., text/plain), some proxies might alter how the body is handled, potentially leading to URL-encoding artifacts in the raw string.
If you are using a framework like Laravel, the framework handles this parsing automatically via request classes, abstracting away the need to manually inspect php://input. For custom scripts or microservices, understanding that file_get_contents returns raw bytes is crucial. If you see URL-encoded characters in your debug output, it often indicates that the data has passed through a proxy (like Nginx or Apache) that attempted to interpret or modify the body based on specific configuration rules before passing it to PHP-FPM.
Conclusion
The behavior of file_get_contents('php://input') returning a string is by design. It provides low-level access to the request body, allowing developers to stream large files or handle complex binary protocols. When working with JSON, you must manually decode the string and validate the result. Always check for decoding errors and ensure that the input stream matches the expected format before accessing object properties.