Parse Request Body using request_parse_body in PHP 8.4

Parse Request Body using request_parse_body in PHP 8.4

PHP automatically parses HTTP POST requests with the application/x-www-form-urlencoded or multipart/form-data content types, populating the $_POST and $_FILES global variables. However, HTTP requests using other methods, such as PUT or PATCH, are not parsed automatically. In these cases, it is the responsibility of the PHP application to handle and parse the request data. Parsing large amounts of data in a PHP application can be inefficient and impact performance.

Since PHP 8.4, the request_parse_body function can be used to read and parse the request body. It is primarily designed to handle application/x-www-form-urlencoded or multipart/form-data content type requests for HTTP methods other than POST.

<?php

[$_POST, $_FILES] = request_parse_body();

var_dump($_POST);

For testing purposes, a PUT request can be sent using Curl as shown below:

curl -X PUT -d "name=John&age=20" http://localhost/main.php

The output will look like this:

array(2) {
  ["name"]=>
  string(4) "John"
  ["age"]=>
  string(2) "20"
}

Leave a Comment

Cancel reply

Your email address will not be published.