Home > Backend Development > PHP Tutorial > How Do I Access a JSON POST Body in PHP?

How Do I Access a JSON POST Body in PHP?

Linda Hamilton
Release: 2024-12-18 03:13:10
Original
735 people have browsed it

How Do I Access a JSON POST Body in PHP?

Accessing JSON POST Body in PHP

In PHP, accessing the JSON body of a POST request requires a specific method. While $_POST cannot handle JSON data, the php://input stream can be utilized to retrieve it.

To obtain the body of a JSON POST request, follow these steps:

  1. Fetch the Raw Request Body:
    Use file_get_contents('php://input') or stream_get_contents(STDIN) to access the request body.
$requestBody = file_get_contents('php://input'); // or stream_get_contents(STDIN)
Copy after login
  1. Parse the JSON Body:
    Decode the JSON string using a JSON parser to extract the desired data.
$data = json_decode($requestBody);
Copy after login
  1. Access the Data:
    You can now access the data from the decoded JSON object.
$value = $data->a; // In your example, this would be 1
Copy after login

Note:

  • The php://input stream can only be read once, so it's advisable to store it in a temporary stream if necessary.
  • This method is not suitable for multipart/form-data requests, as the data is already parsed into $_POST.

The above is the detailed content of How Do I Access a JSON POST Body in PHP?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template