Home >Backend Development >PHP Tutorial >How Can I Properly Read JSON POST Data in PHP?
When working with web services that require JSON-formatted data to be posted, it is essential to correctly handle the POST values in PHP. This article will guide you through the steps to effectively read and parse JSON POST data.
If you are experiencing issues with empty $_POST values despite specifying application/json as the Content-Type, it is likely due to the way you are filtering the post values. In this case, the conventional $_POST variable is not suitable for reading JSON-formatted data.
To access the raw JSON POST data, you need to use file_get_contents('php://input'). This function reads the input stream of the current script and returns the raw HTTP request body.
Updated PHP code on the receiving end:
$json = file_get_contents('php://input'); $obj = json_decode($json);
When testing your web service, it is crucial to ensure that the POST data is sent in the correct format. In your test code:
Updated test code:
$data_string = json_encode($data); $ch = curl_init('http://webservice.local/'); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST"); curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_HTTPHEADER, array( 'Content-Type: application/json', 'Content-Length: ' . strlen($data_string)) ); $result = curl_exec($ch); $result = json_decode($result);
Ensure that header('Content-type: application/json') is called only once on the receiving end.
The above is the detailed content of How Can I Properly Read JSON POST Data in PHP?. For more information, please follow other related articles on the PHP Chinese website!