Parsing PUT and PATCH bodies with request_parse_body
suggest changePHP fills $_POST and $_FILES only for POST requests. A REST API also gets form data with PUT, PATCH and sometimes DELETE. For those methods PHP leaves the body alone and both superglobals stay empty.
Before PHP 8.4 you had two options: run parse_str() on php://input, which only handles urlencoded bodies, or parse multipart/form-data yourself. PHP 8.4 added request_parse_body(), which runs the same parser PHP uses for POST on the body of any request:
request_parse_body(?array $options = null): array
It returns a two-element list [$post, $files] with the same structure as $_POST and $_FILES.
This article covers:
- why
$_POSTand$_FILESare empty forPUTandPATCH - parsing multipart and urlencoded bodies with
request_parse_body() - per-call limits in the
$optionsarray - handling
RequestParseBodyException - a small REST endpoint that accepts form data, JSON and a file upload
All examples need PHP 8.4 or newer. They were run with PHP 8.5 using PHP's built-in web server (php -S 127.0.0.1:<port>) and requests sent with curl.
Related topics: Reading POST data, Reading raw POST data, Uploading files with HTTP PUT (for a raw file as the whole body), Handling file upload errors and REST APIs.
Why $_POST is empty for PUT and PATCH
Save this as dump.php:
<?php
header('Content-Type: text/plain');
echo $_SERVER['REQUEST_METHOD'], "\n";
echo '$_POST: ', json_encode($_POST), "\n";
echo '$_FILES: ', json_encode(array_keys($_FILES)), "\n";
Then send the same multipart form with three methods:
for m in POST PUT PATCH; do
curl -s -X $m -F name=Ann -F file=@people.csv http://127.0.0.1:8123/dump.php
done
Output:
POST
$_POST: {"name":"Ann"}
$_FILES: ["file"]
PUT
$_POST: []
$_FILES: []
PATCH
$_POST: []
$_FILES: []
The body was sent all three times, but PHP parsed it only for POST. It's still there for PUT and PATCH; you just have to ask for it.
Basic usage
Call request_parse_body() once and destructure the result. This is parse.php:
<?php
header('Content-Type: text/plain');
[$post, $files] = request_parse_body();
echo $_SERVER['REQUEST_METHOD'], "\n";
print_r($post);
foreach ($files as $field => $file) {
printf("%s: %s, %d bytes, error %d\n", $field, $file['name'], $file['size'], $file['error']);
}
A multipart PUT with array fields and a file:
curl -s -X PUT -F name=Ann -F 'roles[]=admin' -F 'roles[]=dev' \
-F 'address[city]=Oslo' -F file=@people.csv http://127.0.0.1:8123/parse.php
Output:
PUT
Array
(
[name] => Ann
[roles] => Array
(
[0] => admin
[1] => dev
)
[address] => Array
(
[city] => Oslo
)
)
file: people.csv, 20 bytes, error 0
A urlencoded PATCH (curl -d sends application/x-www-form-urlencoded):
curl -s -X PATCH -d 'name=Ann&roles[]=admin' http://127.0.0.1:8123/parse.php
Output:
PATCH
Array
(
[name] => Ann
[roles] => Array
(
[0] => admin
)
)
What you get back is what $_POST and $_FILES would contain for a POST:
$postuses the same bracket syntax for nested arrays as Passing arrays by POST.- Each entry in
$fileshas the usualname,full_path,type,tmp_name,errorandsizekeys. - The temporary files count as uploaded files:
is_uploaded_file()returnstrueandmove_uploaded_file()works on them. PHP deletes them at the end of the request if you don't move them. - A
charsetparameter in the content type, as inapplication/x-www-form-urlencoded; charset=UTF-8, is fine.
request_parse_body() doesn't write to $_POST or $_FILES. Pass the returned arrays to whatever code needs them.
What it doesn't parse
The function only handles the two form encodings, multipart/form-data and application/x-www-form-urlencoded. Anything else throws a RequestParseBodyException. Here is errors.php:
<?php
header('Content-Type: text/plain');
try {
[$post, $files] = request_parse_body();
echo "ok: ", json_encode($post), "\n";
} catch (RequestParseBodyException $e) {
http_response_code(400);
echo get_class($e), ': ', $e->getMessage(), "\n";
}
Some requests it rejects:
curl -s -X PUT -H 'Content-Type: application/json' -d '{"name":"Ann"}' http://127.0.0.1:8123/errors.php
curl -s -X PUT -H 'Content-Type: text/csv' --data-binary @people.csv http://127.0.0.1:8123/errors.php
curl -s -X PUT http://127.0.0.1:8123/errors.php
curl -s -X PUT -H 'Content-Type: multipart/form-data' --data-binary 'garbage' http://127.0.0.1:8123/errors.php
Output:
RequestParseBodyException: Content-Type "application/json" is not supported
RequestParseBodyException: Content-Type "text/csv" is not supported
RequestParseBodyException: Request does not provide a content type
RequestParseBodyException: Missing boundary in multipart/form-data POST data
RequestParseBodyException extends Exception and its code is always 0, so you can tell failures apart only by the message. If you need different HTTP status codes, check the content type and length yourself before calling, as the REST example below does.
For a JSON body, read php://input and decode it with json_decode() (see Validating JSON with json_validate). For a raw file as the whole body, stream php://input as shown in Uploading files with HTTP PUT.
Limits and the $options array
The parser uses the same php.ini limits as for POST. The $options array overrides them for this call only. These are the only allowed keys:
| Option | Default in php.ini | What happens when it's exceeded |
|---|---|---|
post_max_size |
8M |
exception |
upload_max_filesize |
2M |
that file gets error = UPLOAD_ERR_INI_SIZE (1) |
max_file_uploads |
20 |
exception |
max_input_vars |
1000 |
exception (multipart), warning (urlencoded) |
max_multipart_body_parts |
-1 (falls back to max_input_vars + max_file_uploads) |
exception |
Values take either an int or an ini-style size string such as '4K' or '10M'. An unknown key throws a ValueError like Invalid key "foo" in $options argument.
limits.php uses very small limits so they're easy to hit:
<?php
header('Content-Type: text/plain');
try {
[$post, $files] = request_parse_body([
'post_max_size' => '4K',
'upload_max_filesize' => '500',
'max_file_uploads' => 2,
'max_input_vars' => 10,
'max_multipart_body_parts' => 12,
]);
} catch (RequestParseBodyException $e) {
http_response_code(400);
exit($e->getMessage() . "\n");
}
echo 'fields: ', implode(', ', array_keys($post)), "\n";
foreach ($files as $field => $file) {
printf("%s: %s, %d bytes, error %d\n", $field, $file['name'], $file['size'], $file['error']);
}
Requests (big.txt is 600 bytes, huge.txt is 5000 bytes):
U=http://127.0.0.1:8123/limits.php
curl -s -X PUT -F a=1 -F f=@people.csv $U
curl -s -X PUT -F a=1 -F f=@big.txt $U
curl -s -X PUT -F f1=@a.txt -F f2=@a.txt -F f3=@a.txt $U
curl -s -X PUT -F f=@huge.txt $U
curl -s -X PUT $(for i in $(seq 1 11); do printf -- "-F v$i=1 "; done) $U
curl -s -X PUT $(for i in $(seq 1 13); do printf -- "-F v$i=1 "; done) $U
Output:
fields: a
f: people.csv, 20 bytes, error 0
fields: a
f: big.txt, 0 bytes, error 1
Maximum number of allowable file uploads has been exceeded
POST Content-Length of 5195 bytes exceeds the limit of 4096 bytes
Input variables exceeded 10. To increase the limit change max_input_vars in php.ini.
Multipart body parts limit exceeded 12. To increase the limit change max_multipart_body_parts in php.ini.
The messages are the ones PHP uses for POST, so they say "POST" and "php.ini" even for a PUT with limits set in $options. Rewrite them before you show them to a client.
A file that's too large doesn't fail the whole request. It shows up in $files with an error code and an empty tmp_name, just like with POST, so check error for every file. Handling file upload errors lists the codes.
For urlencoded bodies, going over max_input_vars emits a warning and drops the extra variables instead of throwing:
curl -s -X PATCH -d 'a=1&b=2&c=3&d=4&e=5' http://127.0.0.1:8123/limits-urlencoded.php
Warning: request_parse_body(): Input variables exceeded 2. To increase the limit change max_input_vars in php.ini. in limits-urlencoded.php on line 4
{"a":"1","b":"2","c":"3"}
(The built-in server prints the warning as HTML. It's shown here as plain text with the path shortened. limits-urlencoded.php calls request_parse_body(['max_input_vars' => 2]) and prints json_encode($post).) Count the fields yourself if a truncated body would be a problem.
Lower limits are useful for an endpoint that only takes a few small fields. Higher limits let one upload endpoint accept larger files without raising upload_max_filesize for the whole site. The web server may have its own body size limit (client_max_body_size in nginx, LimitRequestBody in Apache), and request_parse_body() can't raise that.
Gotchas
Call it once, and don't read php://input first. The function reads the request body stream:
- If you
file_get_contents('php://input')before calling it, the body has already been consumed and you get two empty arrays, with no exception. - After a multipart parse,
php://inputis empty. - A second call returns
[[], []]. Worse, after a second call the files from the first call no longer count as uploaded:is_uploaded_file()returnsfalse,move_uploaded_file()fails and the temporary files aren't deleted at the end of the request.
Parse the body in one place (a middleware or a request object) and pass the arrays around.
It returns nothing useful for normal POST requests. With the default enable_post_data_reading=1, PHP has already parsed a POST body into $_POST and $_FILES, and request_parse_body() returns [[], []]. Use the superglobals for POST, or handle both cases in one helper:
function form_body(): array
{
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
return [$_POST, $_FILES];
}
return request_parse_body();
}
If you set enable_post_data_reading=0 (to stream large POST uploads yourself, for example), PHP doesn't parse POST bodies, and request_parse_body() then works for POST too.
Older PHP versions. Before 8.4 the usual approach for urlencoded bodies was:
<?php
header('Content-Type: text/plain');
// Before PHP 8.4: works for urlencoded bodies only
parse_str(file_get_contents('php://input'), $fields);
print_r($fields);
curl -s -X PATCH -d 'name=Ann&roles[]=admin' http://127.0.0.1:8123/legacy.php
Array
(
[name] => Ann
[roles] => Array
(
[0] => admin
)
)
parse_str() doesn't enforce max_input_vars and can't parse multipart bodies, so file uploads over PUT needed a userland multipart parser. On 8.4+, use request_parse_body().
A REST endpoint with PUT and PATCH
This users.php stores users in a JSON file and supports:
GET /users.php?id=1: return the userPATCH /users.php?id=1: change only the fields that were sent, as urlencoded, multipart or JSONPUT /users.php?id=1: replace the user;nameandemailare required, plus an optionalavatarfile upload
read_body() checks the content type and length first, so it can return 413 and 415 instead of a generic 400:
<?php
const MAX_BODY = 2 * 1024 * 1024; // 2 MB
const DB_FILE = __DIR__ . '/users.json';
function respond(int $status, array $data): never
{
http_response_code($status);
header('Content-Type: application/json');
echo json_encode($data, JSON_UNESCAPED_SLASHES), "\n";
exit;
}
/** @return array{0: array, 1: array} fields and files of the request body */
function read_body(): array
{
$length = (int) ($_SERVER['CONTENT_LENGTH'] ?? 0);
if ($length > MAX_BODY) {
respond(413, ['error' => 'body too large']);
}
$type = strtolower(strtok($_SERVER['CONTENT_TYPE'] ?? '', ';'));
switch ($type) {
case 'application/json':
try {
$data = json_decode(file_get_contents('php://input'), true, 32, JSON_THROW_ON_ERROR);
} catch (JsonException $e) {
respond(400, ['error' => 'invalid JSON: ' . $e->getMessage()]);
}
return [is_array($data) ? $data : [], []];
case 'application/x-www-form-urlencoded':
case 'multipart/form-data':
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
return [$_POST, $_FILES]; // PHP already parsed it
}
try {
return request_parse_body([
'post_max_size' => MAX_BODY,
'upload_max_filesize' => '1M',
'max_file_uploads' => 1,
]);
} catch (RequestParseBodyException $e) {
respond(400, ['error' => $e->getMessage()]);
}
default:
respond(415, ['error' => "unsupported content type '$type'"]);
}
}
$users = json_decode(file_get_contents(DB_FILE), true);
$id = $_GET['id'] ?? '';
if (!isset($users[$id])) {
respond(404, ['error' => "no user '$id'"]);
}
switch ($_SERVER['REQUEST_METHOD']) {
case 'GET':
respond(200, $users[$id]);
case 'PATCH': // partial update: only the fields that were sent
[$fields] = read_body();
$changes = array_intersect_key($fields, ['name' => 1, 'email' => 1]);
if (isset($changes['email']) && !filter_var($changes['email'], FILTER_VALIDATE_EMAIL)) {
respond(422, ['error' => 'invalid email']);
}
$users[$id] = array_merge($users[$id], $changes);
break;
case 'PUT': // full replacement: name and email are required, avatar is optional
[$fields, $files] = read_body();
if (!isset($fields['name'], $fields['email'])) {
respond(422, ['error' => 'name and email are required']);
}
$user = ['name' => $fields['name'], 'email' => $fields['email'], 'avatar' => null];
$avatar = $files['avatar'] ?? null;
if ($avatar !== null) {
if ($avatar['error'] !== UPLOAD_ERR_OK) {
respond(422, ['error' => "avatar upload failed with code {$avatar['error']}"]);
}
$target = __DIR__ . "/avatars/$id.png";
if (!move_uploaded_file($avatar['tmp_name'], $target)) {
respond(500, ['error' => 'could not store avatar']);
}
$user['avatar'] = "avatars/$id.png ({$avatar['size']} bytes)";
}
$users[$id] = $user;
break;
default:
header('Allow: GET, PUT, PATCH');
respond(405, ['error' => 'method not allowed']);
}
file_put_contents(DB_FILE, json_encode($users, JSON_PRETTY_PRINT));
respond(200, $users[$id]);
Start with users.json containing {"1": {"name": "Ann", "email": "ann@example.com", "avatar": null}} and an empty avatars directory. In the output below, the HTTP status code (from curl -w '%{http_code}') is added at the end of each line:
U=http://127.0.0.1:8123/users.php
curl -s "$U?id=1"
curl -s -X PATCH -d 'email=ann@example.org' "$U?id=1"
curl -s -X PATCH -H 'Content-Type: application/json' -d '{"name": "Ann Lee"}' "$U?id=1"
curl -s -X PUT -F name=Ann -F email=ann@example.net -F avatar=@ann.png "$U?id=1"
curl -s -X PUT -F name=Ann "$U?id=1"
curl -s -X PATCH -d 'email=nope' "$U?id=1"
curl -s -X PATCH -H 'Content-Type: text/plain' -d 'hello' "$U?id=1"
curl -s -X PATCH -H 'Content-Type: application/json' -d '{"name": ' "$U?id=1"
curl -s -X PUT -F name=Ann -F email=a@b.c -F avatar=@ann.png -F extra=@a.txt "$U?id=1"
curl -s -X PUT -F name=Ann -F email=a@b.c -F avatar=@big.bin "$U?id=1" # 3 MB
curl -s -X DELETE "$U?id=1"
curl -s "$U?id=2"
Output:
{"name":"Ann","email":"ann@example.com","avatar":null} 200
{"name":"Ann","email":"ann@example.org","avatar":null} 200
{"name":"Ann Lee","email":"ann@example.org","avatar":null} 200
{"name":"Ann","email":"ann@example.net","avatar":"avatars/1.png (1024 bytes)"} 200
{"error":"name and email are required"} 422
{"error":"invalid email"} 422
{"error":"unsupported content type 'text/plain'"} 415
{"error":"invalid JSON: Syntax error"} 400
{"error":"Maximum number of allowable file uploads has been exceeded"} 400
{"error":"body too large"} 413
{"error":"method not allowed"} 405
{"error":"no user '2'"} 404
Notes on the design:
- PATCH vs PUT.
PATCHmerges only the keys it received, so-d 'email=...'leavesnameunchanged.PUTreplaces the whole resource, so it requires every field, and leaving outavatarclears it. - Whitelist the fields.
array_intersect_key()drops anything the client sent that isn't an editable field. Parsing the body doesn't validate it: check types and formats (here withfilter_var()) before you save. - Status codes. 415 for a content type you don't accept, 413 for an oversized body, 400 for a body that can't be parsed, and 422 for a body that parses but fails validation.
- Content-Length check. The early
CONTENT_LENGTHcheck gives a clear 413. Thepost_max_sizeoption still guards the parser if that header is missing or wrong. - One parse per request.
read_body()runs once per request, which avoids the double-call problem described above. - Uploads. The avatar goes through
move_uploaded_file()exactly like aPOSTupload. In real code, also check the file's actual type (for example withfinfo) and never use the client-suppliednameas the target path. See Uploading files in the security chapter.
Summary
- PHP parses request bodies into
$_POSTand$_FILESonly forPOST. request_parse_body()(PHP 8.4+) parses amultipart/form-dataorapplication/x-www-form-urlencodedbody for any method and returns[$post, $files].- Uploaded files work with
is_uploaded_file()andmove_uploaded_file(), and PHP deletes them at the end of the request. $optionsoverridespost_max_size,upload_max_filesize,max_file_uploads,max_input_varsandmax_multipart_body_partsfor one call.- Unsupported content types, a missing boundary and exceeded limits throw
RequestParseBodyException. An oversized single file is reported through itserrorfield instead. - Call it once per request, don't read
php://inputbefore it, and don't use it for normalPOSTrequests. - JSON bodies still go through
php://inputandjson_decode().