0

I'm trying to get a file extension of a user uploaded image, I have learnt that several approaches exist to achieve this goal. I think this is currently the conversational way of getting the file extension:

$ext = pathinfo($_FILES["userfile"]["name"], PATHINFO_EXTENSION);

However, I find the following method to be more intuitive and memorable:

list(,$ext) = explode("/", $_FILES["userfile"]["type"]);

What are the drawbacks of taking the latter approach?

fubar
  • 16,918
  • 4
  • 37
  • 43
  • 1
    See [`SplFileInfo::getExtension()`](http://php.net/manual/en/splfileinfo.getextension.php) – Will B. Apr 11 '18 at 22:26
  • 1
    What do you want with this "extension"? My client has just send a file with the name `example.f00b4r` and mime type `idunno/f00b4r` - never mind which way you get to the `f00b4r`, what actual value does it contain in your opinion ...? – CBroe Apr 11 '18 at 22:32
  • 2
    The second part of the mimetype definitely does not always match the common extension. – Evert Apr 11 '18 at 22:34
  • Additionally the explode method returns the mime type as declared by the browser and can be spoofed .e.g not validated by PHP, as opposed to just the uploaded file name extension, also spoofable. The extension can be used to obtain the associated mime type, however I recommend instead to validate the source image file with [`exif_imagetype`](http://us3.php.net/manual/en/function.exif-imagetype.php) – Will B. Apr 11 '18 at 22:36
  • I suppose the main drawback of using the second approach to the get the extension is that it has absolutely nothing to do with the file extension. – iainn Apr 11 '18 at 23:05
  • @fyrye thanks for pointing out SplFileInfo::getExtension() , I wasn't aware of it. I also found some useful info regarding mime types [here](https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types). Provided a file was uploaded, I guess this boils down to the question: Does `$_FILES["userfile"]["type"]` always guarantee two strings, separated by a '/' – sakhimpungose Apr 12 '18 at 00:12
  • Not always no. Depending on which file was uploaded, the mime type could also be a `application/octet-stream`, etc. Which again is subject to the client, PHP does not determine the `type` at all. For example a client uploading a [WebP](https://caniuse.com/#feat=webp) image which it does not support, such as IE will return `application/octet-stream` as opposed to chrome which returns `image/webp`. – Will B. Apr 12 '18 at 00:34
  • Mostly agree with fyrye. I've taken to using [mime_content_type](http://php.net/manual/en/function.mime-content-type.php) to determine the actual mime type from content, then compare the extension with the list of extensions for that mime type in /etc/mime.types If it matches one, fine, otherwise, I use the first one on the list. As he mentions. application/octet-stream is uninformative. – wordragon Apr 12 '18 at 03:56

0 Answers0