Search code examples
phpfilenamesfile-extensionfile-type

Suggest file extension from file type


I have an image file name without extension (lets assume it is image_file_name - NOTE IT IS MISSING THE EXTENSION) and I also know the file type (lets assume the file type is image/jpeg). Now is there a php function that returns the file extension given its type? As explained in the following pseudo code:

$extension = get_extension('image/jpeg'); // Will return 'jpg'

$file_name = 'image_file_name' . '.' . $extension; // Will result in $file_name = image_file_name.jpg

Please note that the image above was only an example, the file name could be of any file type, such as a web page file name or anything else. and the extension could be anything as well, it could be html, css ...etc.

Is it possible to do the above? And how?


Solution

  • $ext = substr(image_type_to_extension(exif_imagetype('dev.png')), 1); //example png
    

    This will give you the extension correctly and is more reliable than $_FILE['image']['type'].