26

Is there a quick and dirty mapping of MIME types to extensions in PHP that I can make use of?

chaos
  • 122,029
  • 33
  • 303
  • 309
Alexander Trauzzi
  • 7,277
  • 13
  • 68
  • 112
  • People merely wanting to map *extensions* to *MIME types*, rather than the other way round, should note that there is now built-in support for this which they should take advantage of - see [Jorge's answer](http://stackoverflow.com/a/20494035/1709587) rather than the accepted one. – Mark Amery Jun 21 '14 at 22:05
  • 1
    @MarkAmery however as noted, finfo_file() requires that the file exists. Which isn't always the case. Chaos' answer is still more on point to the OP and still valid 8 years later. – Wranorn Jan 18 '18 at 06:09

5 Answers5

23

Not built-in, but it's not terribly hard to roll your own:

function system_extension_mime_types() {
    # Returns the system MIME type mapping of extensions to MIME types, as defined in /etc/mime.types.
    $out = array();
    $file = fopen('/etc/mime.types', 'r');
    while(($line = fgets($file)) !== false) {
        $line = trim(preg_replace('/#.*/', '', $line));
        if(!$line)
            continue;
        $parts = preg_split('/\s+/', $line);
        if(count($parts) == 1)
            continue;
        $type = array_shift($parts);
        foreach($parts as $part)
            $out[$part] = $type;
    }
    fclose($file);
    return $out;
}

function system_extension_mime_type($file) {
    # Returns the system MIME type (as defined in /etc/mime.types) for the filename specified.
    #
    # $file - the filename to examine
    static $types;
    if(!isset($types))
        $types = system_extension_mime_types();
    $ext = pathinfo($file, PATHINFO_EXTENSION);
    if(!$ext)
        $ext = $file;
    $ext = strtolower($ext);
    return isset($types[$ext]) ? $types[$ext] : null;
}

function system_mime_type_extensions() {
    # Returns the system MIME type mapping of MIME types to extensions, as defined in /etc/mime.types (considering the first
    # extension listed to be canonical).
    $out = array();
    $file = fopen('/etc/mime.types', 'r');
    while(($line = fgets($file)) !== false) {
        $line = trim(preg_replace('/#.*/', '', $line));
        if(!$line)
            continue;
        $parts = preg_split('/\s+/', $line);
        if(count($parts) == 1)
            continue;
        $type = array_shift($parts);
        if(!isset($out[$type]))
            $out[$type] = array_shift($parts);
    }
    fclose($file);
    return $out;
}

function system_mime_type_extension($type) {
    # Returns the canonical file extension for the MIME type specified, as defined in /etc/mime.types (considering the first
    # extension listed to be canonical).
    #
    # $type - the MIME type
    static $exts;
    if(!isset($exts))
        $exts = system_mime_type_extensions();
    return isset($exts[$type]) ? $exts[$type] : null;
}
chaos
  • 122,029
  • 33
  • 303
  • 309
5

You could use mime_content_type but it is deprecated. Use fileinfo instead:

function getMimeType($filename) {
    $finfo = finfo_open(FILEINFO_MIME_TYPE);
    $mime = finfo_file($finfo, $filename);
    finfo_close($finfo);
    return $mime;
}
Jorge Barata
  • 2,227
  • 1
  • 20
  • 26
  • 5
    It's worth noting that the OP actually asked to map MIME types *to* file extensions. This still covers the most common use case (and probably the one the OP was faced with), so it certainly deserves to exist and I've +1ed it, but it's *not* strictly an answer to the question that was asked as pedantically interpreted. – Mark Amery Jun 21 '14 at 21:58
  • 12
    Note: `finfo_file()` and `mime_content_type()` requires that file exists. – Pang Aug 26 '14 at 03:59
  • 7
    Where does it say that it is deprecated? – Greg Sep 07 '16 at 09:16
  • This fails unless $filename is a string that it can read. It does not work on generic strings that do not correspond to files on the server. – kloddant Jun 30 '21 at 19:49
  • Small note: unfortunately both of those functions fail to provide the correct mimetype because they check the file magic number. ie, for css/js files, you'll just get `text/plain`. Ironically, even PHP avoids those functions for its builtin server and has its own map: https://github.com/php/php-src/blob/d3c86527a5a64ea8fe8279e5099960ede7e3b731/sapi/cli/mime_type_map.h – Christian Sep 28 '22 at 14:32
4

You might want to use this library: https://github.com/ralouphie/mimey

Example usage:

$mimes = new \Mimey\MimeTypes;

// Convert extension to MIME type:
$mimes->getMimeType('json'); // application/json

// Convert MIME type to extension:
$mimes->getExtension('application/json'); // json

This because apparently the quality of the provided PHP functions is dubious.

Rob
  • 4,927
  • 4
  • 26
  • 41
2

If you are working with vary limited extensions of images and need something very simple, I think this is enough.

   switch($info['mime'])
   {
    case 'image/gif'    : $extension = 'gif';   break;
    case 'image/png'    : $extension = 'png';   break;
    case 'image/jpeg'   : $extension = 'jpg';   break;

    default :
        throw new ApplicationException('The file uploaded was not a valid image file.');
    break;
    }
Foreever
  • 7,099
  • 8
  • 53
  • 55
0

use this file : https://github.com/ralouphie/mimey/blob/develop/mime.types.php

like this :

$mimes=include('mime.types.php');

or copy content:

$mime= array (
  'mimes' => 
  array (
    'ez' => 
    array (
      0 => 'application/andrew-inset',
    ),
    'aw' => 
    array (
      0 => 'application/applixware',
    ),
    'atom' => 
    array (
      0 => 'application/atom+xml',
    ),
    'atomcat' => 
    array (
      0 => 'application/atomcat+xml',
    )

  ...

and an example of getting from a stream:

 $finfo = new \finfo(FILEINFO_MIME_TYPE);
 $mime=$finfo->buffer($data);
 $mimes=include(__DIR__."/mime.types.php");
 echo ($mime); //mime
 echo ($mimes['extensions'][$mime]); // file extension
MSS
  • 3,520
  • 24
  • 29