kekos/multipart-form-data-parser
Parse multipart/form-data bodies in PHP, including raw HTTP input. Useful for handling file uploads and form fields when your environment doesn’t populate $_FILES/$_POST (e.g., non-standard servers, PUT/PATCH requests).
Installation
composer require kekos/multipart-form-data-parser
No additional configuration is required—just autoload the package.
Basic Usage
Parse a raw multipart request body (e.g., from $request->getContent() in Laravel):
use Kekos\MultipartFormDataParser\Parser;
$parser = new Parser();
$parsedData = $parser->parse($rawRequestBody);
Output will be an associative array with keys like:
files (for uploaded files)fields (for form fields)First Use Case: File Uploads Handle a file upload endpoint:
$rawBody = $request->getContent();
$parsed = $parser->parse($rawBody);
foreach ($parsed['files'] as $file) {
$path = $file->move(storage_path('app/uploads'), $file->getClientOriginalName());
}
Extract Raw Body
Laravel’s Illuminate\Http\Request provides $request->getContent() for raw body access.
$rawBody = $request->getContent();
Parse and Validate
$parser = new Parser();
$data = $parser->parse($rawBody);
if (empty($data['files'])) {
return response()->json(['error' => 'No files uploaded'], 400);
}
Process Files/Fields
$data['files'] (instances of UploadedFile or similar).$data['fields'] as a flat array.Integration with Laravel’s Request
For seamless use, extend Laravel’s Request class:
// app/Providers/AppServiceProvider.php
use Kekos\MultipartFormDataParser\Parser;
public function boot()
{
Request::macro('parseMultipart', function () {
$parser = new Parser();
return $parser->parse($this->getContent());
});
}
Usage:
$data = $request->parseMultipart();
Override default file handling (e.g., for S3 uploads):
foreach ($data['files'] as $file) {
$s3->putObject([
'Bucket' => 'my-bucket',
'Key' => $file->getClientOriginalName(),
'Body' => fopen($file->getPathname(), 'r'),
]);
}
Boundary Detection
Content-Type boundary. If malformed, parsing fails silently.Large File Handling
Symfony\Component\HttpFoundation\File\UploadedFile for streaming:
$file = new UploadedFile($tempPath, $file->getClientOriginalName());
Nested Multipart
league/mime-type-detection.\Log::debug('Raw body:', [$request->getContent()]);
Content-Type header matches the actual boundary in the body.Custom File Classes Replace the default file object by extending the parser:
$parser = new Parser();
$parser->setFileClass(MyCustomUploadedFile::class);
Field Validation
Validate parsed fields using Laravel’s Validator:
$validator = Validator::make($data['fields'], [
'email' => 'required|email',
]);
Performance For high-traffic APIs, instantiate the parser once (e.g., in a service container):
$app->singleton(Parser::class, function () {
return new Parser();
});
How can I help you explore Laravel packages today?