Skip to content

Instantly share code, notes, and snippets.

@Zegnat
Created April 24, 2018 17:30
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save Zegnat/baf88c68b517076a1baf6d67ce3a5364 to your computer and use it in GitHub Desktop.
Example of using a PSR-7 library to parse an incoming request that contains one or more `photo` uploads.
<?php
use \Nyholm\Psr7\Factory\ServerRequestFactory;
// Use the (draft) PSR-17 Factory to create our PSR-7 Request object:
$incomingRequest = ServerRequestFactory::createServerRequestFromGlobals();
// Check for uploaded files on the Request object.
// @see https://www.php-fig.org/psr/psr-7/#16-uploaded-files
$files = $incomingRequest->getUploadedFiles();
if (isset($files['photo'])) {
// Sadly PSR-7 does not normalise single files v.s. multiple files.
// If it is a single file, still wrap it in an array so we can loop later:
if (!is_array($files['photo'])) {
$files['photo'] = [ $files['photo'] ];
}
foreach ($files['photo'] as $photo) {
// Here $photo is a standardised object per PSR-7 UploadedFileInterface
// @see https://www.php-fig.org/psr/psr-7/#36-psrhttpmessageuploadedfileinterface
// Lets use the PSR given example code to save it to disk:
$filename = sprintf(
'%s.%s',
create_uuid(),
pathinfo($photo->getClientFilename(), PATHINFO_EXTENSION)
);
$photo->moveTo('photos/' . $filename);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment