When to use Symfony's UploadedFile guessClientExtension() vs guessExtension()?

Viewed 677

Uploading a file from a ReactJS/Javascript front end App to a Symfony 4 Backend, I try to get its file extension.

With the file received, I instantiate an UploadedFile object, whichhas the following methods available:

$uploadedFile->getClientOriginalExtension();
$uploadedFile->getClientMimeType();
$uploadedFile->guessClientExtension();
$uploadedFile->guessExtension();

I would expect those getters to return consistent results but it is not really what happens.

Return results for an uploaded file with named image-ile.jpg are :

getClientOriginalExtension() -> ''
getClientMimeType()          -> 'application/octet-stream'
guessClientExtension()       -> 'bin'
guessExtension()             -> 'jpeg'
`

Image file is sent using javascript FormData, with `Content-Type: multipart/form-data`:

> ------WebKitFormBoundaryvFjJSluadmvCob6T
Content-Disposition: form-data; name="image-ile.jpg"; filename="image-ile.jpg"
Content-Type: image/jpeg

In my case, the `guessClientExtension()` doesn't return the relevant file extension while the `guessExtension()` does. So in which cases should I use one getter instead of the other one?
1 Answers

Most often, you should use guessExtension() over guessClientExtenstion().

The latter users the client provided mime-type to ascertain what extension the file is. But I can send you a Word file setting the mime-type image/jpg, and you would be setting the incorrect extension.

As with most things, trusting the client is never a very good practice, unless you have a very specific reason to do so.

When to use this value is completely application dependant, but there can be cases where you are interested in knowing what meta-data the client actually sent. There is no definitive list of "use it when", just that sometimes is needed. Logging and debugging come to mind.

But the short of it is: unless you have a specific use-case for guessClientExtension(), you are likely interested in guessExtension().

If you check the source code for each function (which you could have done in your own IDE) you'll see this comment for guessClientExtension():

/**
 * Returns the extension based on the client mime type.
 *
 * If the mime type is unknown, returns null.
 *
 * This method uses the mime type as guessed by getClientMimeType()
 * to guess the file extension. As such, the extension returned
 * by this method cannot be trusted.
 *
 * For a trusted extension, use guessExtension() instead (which guesses
 * the extension based on the guessed mime type for the file).

guessExtension() is actually defined on File, and ascertains the file extension from guessing the mime-type for the actual file uploaded, not from any meta-data provided by the client.

Related