Slim 3

PSR-7 file uploads in Slim 3

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.phtml contains the form:

      

Upload a file

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 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!

Источник

Uploading files using POST forms

Files that are uploaded using forms in POST requests can be retrieved with the getUploadedFiles method of the Request object.

When uploading files using a POST request, make sure your file upload form has the attribute enctype="multipart/form-data" otherwise getUploadedFiles() will return an empty array.

If multiple files are uploaded for the same input name, add brackets after the input name in the HTML, otherwise only one uploaded file will be returned for the input name by getUploadedFiles() .

Below is an example HTML form that contains both single and multiple file uploads.

  method="post" enctype="multipart/form-data">   Add file (single): 
type="file" name="example1"/> Add files (up to 2):
type="file" name="example2[]"/>
type="file" name="example2[]"/> Add files (multiple):
type="file" name="example3[]" multiple="multiple"/> type="submit"/>

Uploaded files can be moved to a directory using the moveTo method. Below is an example application that handles the uploaded files of the HTML form above.

 require_once __DIR__ . '/vendor/autoload.php'; use Slim\Http\Request; use Slim\Http\Response; use Slim\Http\UploadedFile; $app = new \Slim\App(); $container = $app->getContainer(); $container['upload_directory'] = __DIR__ . '/uploads'; $app->post('/', function(Request $request, Response $response)  $directory = $this->get('upload_directory'); $uploadedFiles = $request->getUploadedFiles(); // handle single input with single file upload $uploadedFile = $uploadedFiles['example1']; if ($uploadedFile->getError() === UPLOAD_ERR_OK)  $filename = moveUploadedFile($directory, $uploadedFile); $response->write('uploaded ' . $filename . '
'
); > // handle multiple inputs with the same key foreach ($uploadedFiles['example2'] as $uploadedFile) if ($uploadedFile->getError() === UPLOAD_ERR_OK) $filename = moveUploadedFile($directory, $uploadedFile); $response->write('uploaded ' . $filename . '
'
); > > // handle single input with multiple file uploads foreach ($uploadedFiles['example3'] as $uploadedFile) if ($uploadedFile->getError() === UPLOAD_ERR_OK) $filename = moveUploadedFile($directory, $uploadedFile); $response->write('uploaded ' . $filename . '
'
); > > >); /** * Moves the uploaded file to the upload directory and assigns it a unique name * to avoid overwriting an existing uploaded file. * * @param string $directory directory to which the file is moved * @param UploadedFile $uploadedFile file uploaded file to move * @return string filename of moved file */ function moveUploadedFile($directory, UploadedFile $uploadedFile) $extension = pathinfo($uploadedFile->getClientFilename(), PATHINFO_EXTENSION); $basename = bin2hex(random_bytes(8)); // see http://php.net/manual/en/function.random-bytes.php $filename = sprintf('%s.%0.8s', $basename, $extension); $uploadedFile->moveTo($directory . DIRECTORY_SEPARATOR . $filename); return $filename; > $app->run();

See also

Источник

Uploading files using POST forms

Files that are uploaded using forms in POST requests can be retrieved with the Request method getUploadedFiles() .

When uploading files using a POST request, make sure your file upload form has the attribute enctype="multipart/form-data" otherwise getUploadedFiles() will return an empty array.

If multiple files are uploaded for the same input name, add brackets after the input name in the HTML, otherwise only one uploaded file will be returned for the input name by getUploadedFiles() .

Below is an example HTML form that contains both single and multiple file uploads.

  method="post" enctype="multipart/form-data">   Add file (single): 
type="file" name="example1"/> Add files (up to 2):
type="file" name="example2[]"/>
type="file" name="example2[]"/> Add files (multiple):
type="file" name="example3[]" multiple="multiple"/> type="submit"/>

Uploaded files can be moved to a directory using the moveTo method. Below is an example application that handles the uploaded files of the HTML form above.

 use DI\ContainerBuilder; use Psr\Http\Message\ResponseInterface; use Psr\Http\Message\ServerRequestInterface; use Psr\Http\Message\UploadedFileInterface; use Slim\Factory\AppFactory; require __DIR__ . '/../vendor/autoload.php'; $containerBuilder = new ContainerBuilder(); $container = $containerBuilder->build(); $container->set('upload_directory', __DIR__ . '/uploads'); AppFactory::setContainer($container); $app = AppFactory::create(); $app->post('/', function (ServerRequestInterface $request, ResponseInterface $response)  $directory = $this->get('upload_directory'); $uploadedFiles = $request->getUploadedFiles(); // handle single input with single file upload $uploadedFile = $uploadedFiles['example1']; if ($uploadedFile->getError() === UPLOAD_ERR_OK)  $filename = moveUploadedFile($directory, $uploadedFile); $response->getBody()->write('Uploaded: ' . $filename . '
'
); > // handle multiple inputs with the same key foreach ($uploadedFiles['example2'] as $uploadedFile) if ($uploadedFile->getError() === UPLOAD_ERR_OK) $filename = moveUploadedFile($directory, $uploadedFile); $response->getBody()->write('Uploaded: ' . $filename . '
'
); > > // handle single input with multiple file uploads foreach ($uploadedFiles['example3'] as $uploadedFile) if ($uploadedFile->getError() === UPLOAD_ERR_OK) $filename = moveUploadedFile($directory, $uploadedFile); $response->getBody()->write('Uploaded: ' . $filename . '
'
); > > return $response; >); /** * Moves the uploaded file to the upload directory and assigns it a unique name * to avoid overwriting an existing uploaded file. * * @param string $directory The directory to which the file is moved * @param UploadedFileInterface $uploadedFile The file uploaded file to move * * @return string The filename of moved file */ function moveUploadedFile(string $directory, UploadedFileInterface $uploadedFile) $extension = pathinfo($uploadedFile->getClientFilename(), PATHINFO_EXTENSION); // see http://php.net/manual/en/function.random-bytes.php $basename = bin2hex(random_bytes(8)); $filename = sprintf('%s.%0.8s', $basename, $extension); $uploadedFile->moveTo($directory . DIRECTORY_SEPARATOR . $filename); return $filename; > $app->run();

Источник

Uploading files using POST forms

Files that are uploaded using forms in POST requests can be retrieved with the getUploadedFiles method of the Request object.

When uploading files using a POST request, make sure your file upload form has the attribute enctype="multipart/form-data" otherwise getUploadedFiles() will return an empty array.

If multiple files are uploaded for the same input name, add brackets after the input name in the HTML, otherwise only one uploaded file will be returned for the input name by getUploadedFiles() .

Below is an example HTML form that contains both single and multiple file uploads.

  method="post" enctype="multipart/form-data">   Add file (single): 
type="file" name="example1"/> Add files (up to 2):
type="file" name="example2[]"/>
type="file" name="example2[]"/> Add files (multiple):
type="file" name="example3[]" multiple="multiple"/> type="submit"/>

Uploaded files can be moved to a directory using the moveTo method. Below is an example application that handles the uploaded files of the HTML form above.

 require_once __DIR__ . '/vendor/autoload.php'; use Slim\Http\Request; use Slim\Http\Response; use Slim\Http\UploadedFile; $app = new \Slim\App(); $container = $app->getContainer(); $container['upload_directory'] = __DIR__ . '/uploads'; $app->post('/', function(Request $request, Response $response)  $directory = $this->get('upload_directory'); $uploadedFiles = $request->getUploadedFiles(); // handle single input with single file upload $uploadedFile = $uploadedFiles['example1']; if ($uploadedFile->getError() === UPLOAD_ERR_OK)  $filename = moveUploadedFile($directory, $uploadedFile); $response->write('uploaded ' . $filename . '
'
); > // handle multiple inputs with the same key foreach ($uploadedFiles['example2'] as $uploadedFile) if ($uploadedFile->getError() === UPLOAD_ERR_OK) $filename = moveUploadedFile($directory, $uploadedFile); $response->write('uploaded ' . $filename . '
'
); > > // handle single input with multiple file uploads foreach ($uploadedFiles['example3'] as $uploadedFile) if ($uploadedFile->getError() === UPLOAD_ERR_OK) $filename = moveUploadedFile($directory, $uploadedFile); $response->write('uploaded ' . $filename . '
'
); > > >); /** * Moves the uploaded file to the upload directory and assigns it a unique name * to avoid overwriting an existing uploaded file. * * @param string $directory directory to which the file is moved * @param UploadedFile $uploadedFile file uploaded file to move * @return string filename of moved file */ function moveUploadedFile($directory, UploadedFile $uploadedFile) $extension = pathinfo($uploadedFile->getClientFilename(), PATHINFO_EXTENSION); $basename = bin2hex(random_bytes(8)); // see http://php.net/manual/en/function.random-bytes.php $filename = sprintf('%s.%0.8s', $basename, $extension); $uploadedFile->moveTo($directory . DIRECTORY_SEPARATOR . $filename); return $filename; > $app->run();

See also

Источник

Читайте также:  Add text with image html
Оцените статью