How to Extract JSON Data from a PHP POST Request
When submitting JSON data to a PHP script via a POST request, accessing the body can be confusing. Using var_dump($_POST); will return an empty array.
Solution: Using php://input
To access the request body, PHP provides php://input:
$entityBody = file_get_contents('php://input');
This stream contains the raw POST data. You can also use stream_get_contents(STDIN) as STDIN is an alias for php://input.
注意事项:
function detectRequestBody() { $rawInput = fopen('php://input', 'r'); $tempStream = fopen('php://temp', 'r+'); stream_copy_to_stream($rawInput, $tempStream); rewind($tempStream); return $tempStream; }
Limitations:
php://input is unavailable for requests with Content-Type: multipart/form-data, as PHP handles multipart data natively.
Example:
To access the JSON object {a:1} in your PHP code, use:
$json = json_decode(file_get_contents('php://input')); echo $json->a; // 1
The above is the detailed content of How to Properly Access JSON Data from PHP POST Requests?. For more information, please follow other related articles on the PHP Chinese website!