Home > Backend Development > PHP Tutorial > How to Access JSON POST Request Body in PHP?

How to Access JSON POST Request Body in PHP?

Susan Sarandon
Release: 2024-12-27 06:48:17
Original
110 people have browsed it

How to Access JSON POST Request Body in PHP?

How to Acquire POST Request Body as JSON in PHP?

When submitting JSON data as POST to a PHP page, accessing its value may seem challenging, as var_dump($_POST); returns an empty array. To retrieve the JSON payload, a special input stream is required.

Using php://input or STDIN

To access the raw entity body of a POST request:

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

Alternatively, one can use STDIN:

$entityBody = stream_get_contents(STDIN);
Copy after login

php://input Considerations

  • php://input is a read-only stream.
  • It should be used instead of $HTTP_RAW_POST_DATA as it's more reliable and doesn't depend on php.ini directives.
  • Php://input is not supported for enctype="multipart/form-data" requests.

Preserving Readability of php://input

Since php://input is not seekable, it can only be read once. To preserve the input stream:

function detectRequestBody() {
    $rawInput = fopen('php://input', 'r');
    $tempStream = fopen('php://temp', 'r+');
    stream_copy_to_stream($rawInput, $tempStream);
    rewind($tempStream);

    return $tempStream;
}
Copy after login

Handling Multipart/Form-Data Requests

For multipart/form-data requests, the JSON payload is available directly in the $_POST superglobal.

The above is the detailed content of How to Access JSON POST Request 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