Home >Backend Development >PHP Tutorial >How to Retrieve POST Values with `application/json` Content Type in PHP?

How to Retrieve POST Values with `application/json` Content Type in PHP?

Linda Hamilton
Linda HamiltonOriginal
2024-12-23 15:53:15406browse

How to Retrieve POST Values with `application/json` Content Type in PHP?

Reading JSON POST Using PHP

In this inquiry, the user encounters difficulties in extracting POST values and returning a JSON-encoded array from a web service after transitioning to using a JSON-based content type. The following question arose:

Question:

What is the appropriate method to retrieve POST values when the content type is application/json?

Answer:

Traditional PHP superglobals such as $_POST will not contain the desired data when the content type is application/json. To access the raw POST data, it is necessary to read from a different source.

Solution:

Utilize PHP's file_get_contents() function to retrieve the raw POST input and then parse it using json_decode(). This approach enables accessing the data in an associative array.

Additional Consideration:

The user's testing code also requires modification. CURLOPT_POSTFIELDS should be used to set the request body as a JSON string, rather than attempting to encode it as application/x-www-form-urlencoded.

Updated PHP Code for Testing:

$data_string = json_encode($data);

$curl = curl_init('http://webservice.local/');
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($curl, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HTTPHEADER, array(
        'Content-Type: application/json',
        'Content-Length: ' . strlen($data_string))
);

$result = curl_exec($curl);
$result = json_decode($result);
var_dump($result);

Updated PHP Code for the Web Service:

header('Content-type: application/json');

// Remove duplicate line
// header('Content-type: application/json');

// Remaining code...

The above is the detailed content of How to Retrieve POST Values with `application/json` Content Type in PHP?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn