Created
April 24, 2018 17:30
Star
You must be signed in to star a gist
Example of using a PSR-7 library to parse an incoming request that contains one or more `photo` uploads.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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