1

I'm learning ReactPHP with the Book «ReactPHP for Beginners». Everything worked fine, but now I'm on the section with file uploads.

There is a simple html form:

<!DOCTYPE html>
<html lang="de">
    <head>
        <meta charset="UTF-8" />
        <title>ReactPHP App</title>
        <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" />
    </head>
    <body>
        <div class="container">
            <div class="row">
                <form action="/upload" method="post" enctype="multipart/form-data" class="justify-content-center">
                    <div class="form-group">
                        <label for="file">Submit a file:</label>
                        <input type="file" name="file" id="file" accept="image/x-png,image/jpeg" />
                    </div>
                    <button type="submit" class="btn btn-primary">Submit</button>
                </form>
            </div>
        </div>
    </body>
</html>

And the PHP Code witch receives the form data ist also very simple:

<?php
    use Psr\Http\Message\ServerRequestInterface;
    use React\EventLoop\LoopInterface;
    use React\ChildProcess\Process;
    use React\Http\Message\Response;

    return [
        '/' => function(ServerRequestInterface $request, LoopInterface $loop) {
            $childProcess = new Process('cat pages/index.html', __DIR__);
            $childProcess->start($loop);

            return new Response(
                200,
                ['Content-Type' => 'text/html'],
                $childProcess->stdout
            );
        },
        '/upload' => function (ServerRequestInterface $request, LoopInterface $loop) {
            $files = $request->getUploadedFiles();
            $file = $files['file'];
            print_r($file);
          
            return new Response(
              200, ['Content-Type' => 'text/plain'], ''
            );
          }
    ];

If I choose a JPG-File and click «Submit», $request->getUploadedFiles() always returns an empty array. What's wrong here? I work on Mac OS X (10.15.7) and I tried with different browsers.

Christian
  • 11
  • 1

1 Answers1

0

It looks like that server needs additional middlewares setup to properly handle file upload. You have to import it from React\Http\Middleware\ namespace.

$server = new Server($loop,
    new StreamingRequestMiddleware(),
    new RequestBodyBufferMiddleware(8 * 1024 * 1024), // 8 MiB
    new RequestBodyParserMiddleware(8 * 1024 * 1024, 1), // 8 MiB
    function (ServerRequestInterface $request) use ($router) {
        return $router($request);
});

Those additional midlewares are specific for the web browser as long as ReactPHP is able to handle file upload if we are using curl, e.g.

$ curl --form file=@some_file_that_we_are_going_to_upload http://0.0.0.0:8080/upload

Please have in mind that path and port are related to example from book „ReactPHP for Beginners”

Krzysztof Safjanowski
  • 7,292
  • 3
  • 35
  • 47