Home >Backend Development >PHP Tutorial >How to Read the Body of a JSON POST Request in PHP?

How to Read the Body of a JSON POST Request in PHP?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-15 01:55:12793browse

How to Read the Body of a JSON POST Request in PHP?

Reading the Body of a JSON POST Request in PHP

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

  • Remove one instance of the 'Content-Type: application/json' header from the receiver script, as it should be set only once.
  • Ensure that the sender script is sending a valid JSON string.
  • You can use tools like Postman or Insomnia to easily send JSON POST requests for testing purposes.

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!

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