Home > Backend Development > PHP Tutorial > How to Properly Access JSON POST Data in PHP?

How to Properly Access JSON POST Data in PHP?

Barbara Streisand
Release: 2024-12-22 04:19:12
Original
406 people have browsed it

How to Properly Access JSON POST Data in PHP?

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);
Copy after login

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}
Copy after login

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
Copy after login

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!

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