A browser submits an edited article with a new image. The API uses PATCH because the user is changing an existing resource rather than creating one. The request is multipart/form-data, combining ordinary fields with binary content. Historically, PHP’s convenient $_POST and $_FILES population has been associated with POST requests. Handling other methods often meant using custom parsers or changing the API design to accommodate PHP’s defaults.

PHP 8.4 introduced request_parse_body(), a native way to parse application/x-www-form-urlencoded and multipart/form-data request bodies. The change sounds small, but it removes a recurring source of fragile application code. It also introduces important constraints: the body is consumable only once, parsing has limits, and a successfully parsed file is not automatically safe to trust.

What the function returns

The function returns a pair of arrays: parsed fields and parsed files. The structure resembles $_POST and $_FILES, but it is returned explicitly. A PATCH endpoint can therefore retrieve the input without pretending that the request was a POST. The function is available beginning with PHP 8.4; it is not a polyfill for older runtimes.

[$fields, $files] = request_parse_body();
$title = $fields['title'] ?? null;
$image = $files['image'] ?? null;

The request must carry a supported Content-Type. JSON remains a separate concern: an application accepting application/json should read and decode the body using its normal JSON pathway. Do not attempt to use this parser as a universal HTTP body decoder.

The body belongs to one consumer

The most surprising rule is that request_parse_body() consumes the incoming body. If middleware has already read php://input, the parser may return empty arrays. Conversely, after parsing, the original bytes are not buffered for later use through php://input. That makes middleware ordering an architectural decision, not a cosmetic detail.

An authentication layer that verifies a signature over the raw body needs careful design. It cannot casually read the body and then expect the endpoint to parse it again. Similarly, a logging middleware must not consume arbitrary upload bodies merely to record a debug trace. Decide at the edge of the application which component owns the body, and keep that contract explicit.

A narrowly scoped PATCH handler

This sketch demonstrates parsing and validation. It assumes authentication and authorization have already succeeded. The upload directory must be configured outside publicly executable paths, and the resource identifier must be validated separately.

<?php
declare(strict_types=1);

if ($_SERVER['REQUEST_METHOD'] !== 'PATCH') {
    http_response_code(405);
    exit;
}

try {
    [$fields, $files] = request_parse_body([
        'post_max_size' => '8M',
        'upload_max_filesize' => '6M',
        'max_file_uploads' => 1,
    ]);
} catch (RequestParseBodyException | ValueError $e) {
    http_response_code(400);
    exit('Invalid request body');
}

$title = $fields['title'] ?? null;

if (!is_string($title) || trim($title) === '') {
    http_response_code(422);
    exit('Title is required');
}

$file = $files['image'] ?? null;

if ($file !== null) {
    if (!is_array($file) ||
        $file['error'] !== UPLOAD_ERR_OK) {
        http_response_code(422);
        exit('Invalid upload');
    }

    $mime = (new finfo(FILEINFO_MIME_TYPE))
        ->file($file['tmp_name']);

    if (!in_array(
        $mime,
        ['image/jpeg', 'image/png'],
        true
    )) {
        http_response_code(415);
        exit('Unsupported image');
    }

    $target = '/private/uploads/'
        . bin2hex(random_bytes(16));

    if (!move_uploaded_file(
        $file['tmp_name'],
        $target
    )) {
        http_response_code(500);
        exit('Storage failure');
    }
}

http_response_code(204);

This is an illustrative endpoint, not a complete production API. It does not persist the title, implement resource versioning, inspect image dimensions, or define storage permissions. Those responsibilities must be added rather than silently assumed. The example also deliberately avoids trusting the client-supplied filename or MIME header.

Limits are part of the contract

The optional argument can override selected parsing settings such as post_max_size, upload_max_filesize, max_file_uploads, max_input_vars and max_multipart_body_parts. These limits matter for memory pressure, disk usage and denial-of-service exposure. They are not substitutes for limits enforced by a reverse proxy or web server.

Applications should decide which requests need larger limits and avoid increasing global limits for every endpoint. A profile-picture upload and a bulk media import should not automatically share the same policy. Errors should be translated into useful HTTP responses without exposing server paths or parser internals.

Parsing is not authorization

A multipart request may contain a field called role=admin or status=published. Parsing it does not make it a permitted change. Whitelist fields, validate types, enforce object-level authorization and reject unexpected state transitions. PATCH semantics do not imply that any arbitrary partial update is acceptable.

For files, verify upload status, examine actual content, generate server-controlled names and place storage where uploaded content cannot execute as code. File extensions and user-provided Content-Type values are untrusted hints. Image processing may introduce additional security considerations and resource limits.

What changes for frameworks?

Framework request abstractions may already handle multipart methods differently, and their middleware may own the body. A team should inspect its framework version before invoking request_parse_body() directly. Calling two parsers on the same stream is an integration defect, not extra validation.

The important improvement is that PHP now exposes a native primitive for a previously awkward case. It simplifies one layer of the request pipeline, but does not replace routing, authentication, validation or storage architecture. A good migration removes custom multipart parsing only after tests establish equivalent behavior for successful uploads, malformed bodies, oversized files and repeated requests.

LEAVE A REPLY

Please enter your comment!
Please enter your name here