Home >Backend Development >PHP Tutorial >How Can I Properly Read JSON POST Data in PHP?

How Can I Properly Read JSON POST Data in PHP?

Barbara Streisand
Barbara StreisandOriginal
2024-12-16 19:39:15940browse

How Can I Properly Read JSON POST Data in PHP?

Reading JSON POST Using 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.

Issue: Empty $_POST Values with Application/JSON Content-Type

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.

Solution: Reading JSON with file_get_contents('php://input')

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);

Handling POST Data Correctly During Testing

When testing your web service, it is crucial to ensure that the POST data is sent in the correct format. In your test code:

  • Use json_encode($data) to convert the data into a JSON string.
  • Specify the Content-Type as application/json in the HTTP header.

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);

Note on Header Configuration

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!

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