Accessing POST Data in PHP: Decoding JSON Body
In PHP, handling POST requests requires accessing the request body to extract submitted data. When receiving a JSON-encoded body, it's important to use the appropriate approach to retrieve the desired information.
JSON Extraction
To access the JSON data in the POST body, do not rely on $_POST. Instead, use file_get_contents('php://input'):
$json_input = file_get_contents('php://input'); $data = json_decode($json_input, true);
This reads the raw POST body as a string, which is then decoded into a PHP array using json_decode().
Handling multipart/form-data
If your POST request has multipart/form-data encoding, the data will be parsed automatically into the $_POST superglobal. However, note that you cannot access the raw JSON body using php://input in this case.
Example
For example, if you submit a POST request with the following JSON body:
{"a": 1}
Your PHP code can decode it as follows:
$json_input = file_get_contents('php://input'); $data = json_decode($json_input, true); var_dump($data['a']); // Outputs: 1
Note on Seekability
php://input is not seekable, meaning it can only be read once. If you need to preserve the stream for multiple read operations, consider constructing a temporary stream using stream_copy_to_stream() or using php://temp for better memory management.
The above is the detailed content of How to Properly Access JSON POST Data in PHP?. For more information, please follow other related articles on the PHP Chinese website!