Home >Backend Development >PHP Tutorial >How to Access JSON POST Request Body in PHP?
How to Acquire POST Request Body as JSON in PHP?
When submitting JSON data as POST to a PHP page, accessing its value may seem challenging, as var_dump($_POST); returns an empty array. To retrieve the JSON payload, a special input stream is required.
Using php://input or STDIN
To access the raw entity body of a POST request:
$entityBody = file_get_contents('php://input');
Alternatively, one can use STDIN:
$entityBody = stream_get_contents(STDIN);
php://input Considerations
Preserving Readability of php://input
Since php://input is not seekable, it can only be read once. To preserve the input stream:
function detectRequestBody() { $rawInput = fopen('php://input', 'r'); $tempStream = fopen('php://temp', 'r+'); stream_copy_to_stream($rawInput, $tempStream); rewind($tempStream); return $tempStream; }
Handling Multipart/Form-Data Requests
For multipart/form-data requests, the JSON payload is available directly in the $_POST superglobal.
The above is the detailed content of How to Access JSON POST Request Body in PHP?. For more information, please follow other related articles on the PHP Chinese website!