MIME Info

Component ID

2422367

Component name

MIME Info

Component type

module

Maintenance status

Development status

Component security advisory coverage

covered

Downloads

606

Component created

Component changed

Component body

Developers know that the Drupal determines MIME-type of file by extension, but this is not quite the right way. If I'll change an extension of *.php file to *.jpg, then MIME-type will be determined as image/jpeg but, in fact, it will be the application/x-httpd-php. The MIME Info module solves this problem.

Drupal 8

Adds Symfony MIME type guessers to container and allow to have isSupported() method for every guesser.

Usage

Drupal::service('file.mime_type.guesser')->guess($uri);

Drupal 7

Features

The module provides overrides for three basic stream wrappers - public, private and temporary. If you allow the overriding, the MIME-type of files will be determined with help of FileInfo extension, or, if it does not exist, - by binary data.

Also, if you have non-standard stream wrapper, you can use the mimeinfo($uri) function in getMimeType() method or easily override an object by following the instruction:

  1. Select available wrapper in Override the stream wrappers section on admin/config/media/file-system page.
  2. Add mimeinfo as the dependency to a module that will override a wrapper.
  3. Create the class by following the naming convention rules: MimeInfo<WRAPPER>StreamWrapper. If the wrapper name is test-public_fb@files, then class should be named MimeInfoTestPublicFbFilesStreamWrapper.

Note: If you use extended wrappers and try to get the MIME-type of non-existent file, then the method of default object will be used. Due to that, the MIME-type of non-existent file may differ.

Example of overriding the "Remote" stream wrapper

class MimeInfoRemoteStreamWrapper extends DrupalPublicStreamWrapper {

  /**
   * {@inheritdoc}
   */
  public static function getMimeType($uri, $mapping = NULL) {
    return mimeinfo($uri) ?: parent::getMimeType($uri, $mapping);
  }

}

Known issues

  1. If your PHP version is greater than 5.4 then you'll get a warning message that the stream_cast method is not implemented by Drupal.