Introduction
This article addresses the topic of retrieving and parsing JSON POST requests in PHP. This can be especially useful when working with web services and APIs that transfer data in the JSON format.
Identifying the Issue
When using a content-type of application/json for POST requests, conventional methods such as $_POST will not retrieve the data. This is because these methods expect the request body to be in the form of application/x-www-form-urlencoded data.
Solution: File_get_contents('php://input')
To resolve this issue, PHP provides the file_get_contents('php://input') function, which allows you to read the raw data received in the request body. This raw data can then be parsed using JSON decoding functions.
Updated Code
Sender (CURL)
$ch = curl_init('http://webservice.local/'); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST"); curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data)); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_HTTPHEADER, array( 'Content-Type: application/json', 'Content-Length: ' . strlen(json_encode($data)) )); $result = curl_exec($ch); $result = json_decode($result); var_dump($result);
Receiver (PHP)
$json = file_get_contents('php://input'); $obj = json_decode($json, TRUE);
Additional Notes
The above is the detailed content of How to Read the Body of a JSON POST Request in PHP?. For more information, please follow other related articles on the PHP Chinese website!