Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support multipart parsing for RequestBodyParserMiddleware (file uploads) #226

Merged
merged 1 commit into from
Oct 2, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 22 additions & 6 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -236,10 +236,6 @@ For more details about the request object, check out the documentation of
and
[PSR-7 RequestInterface](https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-7-http-message.md#32-psrhttpmessagerequestinterface).

> Currently the uploaded files are not added by the
`Server`, but you can add these parameters by yourself using the given methods.
The next versions of this project will cover these features.

Note that by default, the request object will be processed once the request headers have
been received (see also [`RequestBodyBufferMiddleware`](#requestbodybuffermiddleware)
for an alternative).
Expand All @@ -265,7 +261,8 @@ designed under the assumption of being in control of the request body.
Given that this does not apply to this server, the following
`PSR-7 StreamInterface` methods are not used and SHOULD NOT be called:
`tell()`, `eof()`, `seek()`, `rewind()`, `write()` and `read()`.
If this is an issue for your use case, it's highly recommended to use the
If this is an issue for your use case and/or you want to access uploaded files,
it's highly recommended to use the
[`RequestBodyBufferMiddleware`](#requestbodybuffermiddleware) instead.
The `ReactPHP ReadableStreamInterface` gives you access to the incoming
request body as the individual chunks arrive:
Expand Down Expand Up @@ -732,7 +729,9 @@ $middlewares = new MiddlewareRunner([
The `RequestBodyParserMiddleware` takes a fully buffered request body (generally from [`RequestBodyBufferMiddleware`](#requestbodybuffermiddleware)),
and parses the forms and uploaded files from the request body.

Parsed submitted forms will be available from `$request->getParsedBody()` as array. For example the following submitted body:
Parsed submitted forms will be available from `$request->getParsedBody()` as
array.
For example the following submitted body (`application/x-www-form-urlencoded`):

`bar[]=beer&bar[]=wine`

Expand All @@ -747,6 +746,23 @@ $parsedBody = [
];
```

Aside from `application/x-www-form-urlencoded`, this middleware handler
also supports `multipart/form-data`, thus supporting uploaded files available
through `$request->getUploadedFiles()`.

The `$request->getUploadedFiles(): array` will return an array with all
uploaded files formatted like this:

```php
$uploadedFiles = [
'avatar' => new UploadedFile(/**...**/),
'screenshots' => [
new UploadedFile(/**...**/),
new UploadedFile(/**...**/),
],
];
```

Usage:

```php
Expand Down
253 changes: 253 additions & 0 deletions src/Middleware/MultipartParser.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,253 @@
<?php

namespace React\Http\Middleware;

use Psr\Http\Message\ServerRequestInterface;
use React\Http\HttpBodyStream;
use React\Http\UploadedFile;
use RingCentral\Psr7;

/**
* @internal
*/
final class MultipartParser
{
/**
* @var string
*/
protected $buffer = '';

/**
* @var string
*/
protected $boundary;

/**
* @var ServerRequestInterface
*/
protected $request;

/**
* @var HttpBodyStream
*/
protected $body;

/**
* @var callable
*/
protected $onDataCallable;

public static function parseRequest(ServerRequestInterface $request)
{
$parser = new self($request);
return $parser->parse();
}

private function __construct(ServerRequestInterface $request)
{
$this->request = $request;
}

private function parse()
{
$this->buffer = (string)$this->request->getBody();

$this->determineStartMethod();

return $this->request;
}

private function determineStartMethod()
{
if (!$this->request->hasHeader('content-type')) {
$this->findBoundary();
return;
}

$contentType = $this->request->getHeaderLine('content-type');
preg_match('/boundary="?(.*)"?$/', $contentType, $matches);
if (isset($matches[1])) {
$this->boundary = $matches[1];
$this->parseBuffer();
return;
}

$this->findBoundary();
}

private function findBoundary()
{
if (substr($this->buffer, 0, 3) === '---' && strpos($this->buffer, "\r\n") !== false) {
$boundary = substr($this->buffer, 2, strpos($this->buffer, "\r\n"));
$boundary = substr($boundary, 0, -2);
$this->boundary = $boundary;
$this->parseBuffer();
}
}

private function parseBuffer()
{
$chunks = explode('--' . $this->boundary, $this->buffer);
$this->buffer = array_pop($chunks);
foreach ($chunks as $chunk) {
$chunk = $this->stripTrailingEOL($chunk);
$this->parseChunk($chunk);
}
}

private function parseChunk($chunk)
{
if ($chunk === '') {
return;
}
clue marked this conversation as resolved.
Show resolved Hide resolved

list ($header, $body) = explode("\r\n\r\n", $chunk, 2);
$headers = $this->parseHeaders($header);

if (!isset($headers['content-disposition'])) {
return;
}

if ($this->headerStartsWith($headers['content-disposition'], 'filename')) {
$this->parseFile($headers, $body);
return;
}

if ($this->headerStartsWith($headers['content-disposition'], 'name')) {
$this->parsePost($headers, $body);
return;
}
}

private function parseFile($headers, $body)
{
if (
!$this->headerContains($headers['content-disposition'], 'name=') ||
!$this->headerContains($headers['content-disposition'], 'filename=')
) {
return;
}

$this->request = $this->request->withUploadedFiles($this->extractPost(
$this->request->getUploadedFiles(),
$this->getFieldFromHeader($headers['content-disposition'], 'name'),
new UploadedFile(
Psr7\stream_for($body),
strlen($body),
UPLOAD_ERR_OK,
$this->getFieldFromHeader($headers['content-disposition'], 'filename'),
$headers['content-type'][0]
)
));
}

private function parsePost($headers, $body)
{
foreach ($headers['content-disposition'] as $part) {
if (strpos($part, 'name') === 0) {
preg_match('/name="?(.*)"$/', $part, $matches);
$this->request = $this->request->withParsedBody($this->extractPost(
$this->request->getParsedBody(),
$matches[1],
$body
));
}
}
}

private function parseHeaders($header)
{
$headers = array();

foreach (explode("\r\n", trim($header)) as $line) {
list($key, $values) = explode(':', $line, 2);
$key = trim($key);
$key = strtolower($key);
$values = explode(';', $values);
$values = array_map('trim', $values);
$headers[$key] = $values;
}

return $headers;
}

private function headerStartsWith(array $header, $needle)
{
foreach ($header as $part) {
if (strpos($part, $needle) === 0) {
return true;
}
}

return false;
}

private function headerContains(array $header, $needle)
{
foreach ($header as $part) {
if (strpos($part, $needle) !== false) {
return true;
}
}

return false;
}

private function getFieldFromHeader(array $header, $field)
{
foreach ($header as $part) {
if (strpos($part, $field) === 0) {
preg_match('/' . $field . '="?(.*)"$/', $part, $matches);
return $matches[1];
}
}

return '';
}

private function stripTrailingEOL($chunk)
{
if (substr($chunk, -2) === "\r\n") {
return substr($chunk, 0, -2);
}

return $chunk;
}

private function extractPost($postFields, $key, $value)
{
$chunks = explode('[', $key);
if (count($chunks) == 1) {
$postFields[$key] = $value;
return $postFields;
}

$chunkKey = $chunks[0];
if (!isset($postFields[$chunkKey])) {
$postFields[$chunkKey] = array();
}

$parent = &$postFields;
for ($i = 1; $i < count($chunks); $i++) {
$previousChunkKey = $chunkKey;
if (!isset($parent[$previousChunkKey])) {
$parent[$previousChunkKey] = array();
}
$parent = &$parent[$previousChunkKey];
$chunkKey = $chunks[$i];

if ($chunkKey == ']') {
$parent[] = $value;
return $postFields;
}

$chunkKey = rtrim($chunkKey, ']');
if ($i == count($chunks) - 1) {
$parent[$chunkKey] = $value;
return $postFields;
}
}

return $postFields;
}
}
5 changes: 5 additions & 0 deletions src/Middleware/RequestBodyParserMiddleware.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,16 @@ final class RequestBodyParserMiddleware
public function __invoke(ServerRequestInterface $request, $next)
{
$type = strtolower($request->getHeaderLine('Content-Type'));
list ($type) = explode(';', $type);

if ($type === 'application/x-www-form-urlencoded') {
return $next($this->parseFormUrlencoded($request));
}

if ($type === 'multipart/form-data') {
return $next(MultipartParser::parseRequest($request));
}

return $next($request);
}

Expand Down
Loading