How to detect MIME-type from PSR-7 UploadedFileInterface

Viewed 579

I have a simple controller that handles image uploads. Before saving the image/file to its final destination i would like to validate the mimeType of that file.

My controller uses Psr\Http\Message\ServerRequestInterface and calls getUploadedFiles() to get the uploaded files as instances of Psr\Http\Message\UploadedFileInterface.

On an instance of that interface I can now call getClientMediaType() to get the mime type.

My problem is that the documentation explicitly states not to trust that value! Because of that i would like to detect the mimeType with mime_content_type() but I cant get the actual filename from that interface.

I see two options:

  • i could just use $_FILES and call mime_content_type($_FILES['files']['tmp_name'])
  • i could move the file and to a place that i know and then call mime_content_type() but that would defeat the purpose of NOT moving the file before validation

Here is a abbreviated version of my controller:

    public function handleUpload(ServerRequestInterface $request, ResponseInterface $response) {
        $files = $request->getUploadedFiles();
        /** @var UploadedFile $uploadedFile */
        $uploadedFile = $files[0];

        $fileType = $uploadedFile->getClientMediaType(); // This need to be replaced !
        if (!in_array($fileType, self::VALID_IMAGE_MIME_TYPE)) {
            // return error
        }

        // do stuff
    }

Is there a method i'm not seeing on how to get the tmp_name from the UploadedFileInterface? Is there another best practise to do this kind of validation? It seems a very obvious problem, so i guess i'm missing something basic.

0 Answers
Related