Handling file uploads in Slim 3 is reasonably easy as it uses the PSR-7 Request object, so let’s take a look.

The easiest way to get a Slim framework project up and running is to use the Slim-Skeleton to create a project:

composer create-project slim/slim-skeleton slim3-file-uploads

and then you can cd into the directory and run the PHP built-in web server using:

php -S 0.0.0.0:8888 -t public public/index.php

Displaying the form

We can now create a simple form, firstly by setting up the / route in src/routes.php:

$app->get('/', function ($request, $response, $args) {
    // Render file upload form
    return $this->renderer->render($response, 'index.phtml', $args);
});

The view script, templates/index.html contains the form:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>Slim 3</title>
        <link rel="stylesheet" href="http://yegor256.github.io/tacit/tacit.min.css">
    </head>
    <body>
        <h1>Upload a file</h1>
        <form method="POST" action="/upload" enctype="multipart/form-data">
            <label>Select file to upload:</label>
            <input type="file" name="newfile">
            <button type="submit">Upload</button>
        </form>
    </body>
</html>

Handling the upload

We now need to write the route that handles the uploaded file. This goes in src/routes.php:

$app->post('/upload', function ($request, $response, $args) {
    $files = $request->getUploadedFiles();
    if (empty($files['newfile'])) {
        throw new Exception('Expected a newfile');
    }

    $newfile = $files['newfile'];
    // do something with $newfile
});

The file upload in $_FILES is available from the $request‘s getUploadedFiles() method. This returns an array keyed by the name of the <input> element. In this case, that’s newfile.

The $newfile object is a instance of PSR-7’s UploadedFileInterface. Typical usage is to check that there is no error and then move the file to somewhere else. This is done like this:

if ($newfile->getError() === UPLOAD_ERR_OK) {
    $uploadFileName = $newfile->getClientFilename();
    $newfile->moveTo("/path/to/$uploadFileName");
}

There’s also other useful methods such as getClientMediaType() and getSize() if you need them.

Conclusion

As you can see, dealing with file uploads within a PSR-7 request is really easy!

Source: AKRABAT

By Rob