
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:
-
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)
-
Parse the JSON Body:
Decode the JSON string using a JSON parser to extract the desired data.
$data = json_decode($requestBody);
-
Access the Data:
You can now access the data from the decoded JSON object.
$value = $data->a; // In your example, this would be 1
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!
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