File extensions lie, or can at least. It is definitely best not to rely on/trust user submitted data. Also, as the PHP manual notes:
$_FILES['userfile']['type'] -
The mime type of the file, if the browser provided this information. An example would be "image/gif". This mime type is however not checked on the PHP side and therefore don't take its value for granted.
This is not reliable.
Here's a better way:
PHP's getimagesize()
function returns a numerically indexed array of data about the image, and index 2 is one of the IMAGETYPE_XXX constants (a full list of which is available here) indicating the type of the image. These can then be used in a number of GD family functions, the two relevant ones being image_type_to_extension()
and image_type_to_mime_type()
.
So, you could easily do something along these lines:
$imageData = getimagesize($_FILES['userfile']['tmp_name']);
// $imageData[2] will contain the value of one of the constants
$mimeType = image_type_to_mime_type($imageData[2]);
$extension = image_type_to_extension($imageData[2]);
Although, iif you have the exif
extension available, the [exif_imagetype()][5]
function will return the exact same result as index 2 of getimagesize()
but is much faster.
I've used the GD methods as my primary example, because they are more commonly present across PHP installs. But the Imagick extension also offers similar functionallity, and you could also verify the mime type with the fileinfo
extension (included since 5.3, btw).