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

How to Properly Access JSON Data from PHP POST Requests?

Barbara Streisand
Barbara StreisandOriginal
2024-12-23 17:26:10673browse

How to Properly Access JSON Data from PHP POST Requests?

How to Extract JSON Data from a PHP POST Request

When submitting JSON data to a PHP script via a POST request, accessing the body can be confusing. Using var_dump($_POST); will return an empty array.

Solution: Using php://input

To access the request body, PHP provides php://input:

$entityBody = file_get_contents('php://input');

This stream contains the raw POST data. You can also use stream_get_contents(STDIN) as STDIN is an alias for php://input.

注意事项:

  • php://input is not seekable, so it can only be read once.
  • For large datasets, consider buffering it with a temporary stream, such as:
function detectRequestBody() {
    $rawInput = fopen('php://input', 'r');
    $tempStream = fopen('php://temp', 'r+');
    stream_copy_to_stream($rawInput, $tempStream);
    rewind($tempStream);

    return $tempStream;
}

Limitations:

php://input is unavailable for requests with Content-Type: multipart/form-data, as PHP handles multipart data natively.

Example:

To access the JSON object {a:1} in your PHP code, use:

$json = json_decode(file_get_contents('php://input'));
echo $json->a; // 1

The above is the detailed content of How to Properly Access JSON Data from PHP POST Requests?. 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