hook_file_mimetype_mapping_alter

7 system.api.php hook_file_mimetype_mapping_alter(&$mapping)
8 system.api.php hook_file_mimetype_mapping_alter(&$mapping)

Alter MIME type mappings used to determine MIME type from a file extension.

This hook is run when file_mimetype_mapping() is called. It is used to allow modules to add to or modify the default mapping from file_default_mimetype_mapping().

Parameters

$mapping: An array of mimetypes correlated to the extensions that relate to them. The array has 'mimetypes' and 'extensions' elements, each of which is an array.

See also

file_default_mimetype_mapping()

Related topics

1 function implements hook_file_mimetype_mapping_alter()

1 invocation of hook_file_mimetype_mapping_alter()

File

modules/system/system.api.php, line 3752
Hooks provided by Drupal core and the System module.

Code

function hook_file_mimetype_mapping_alter(&$mapping) {
  // Add new MIME type 'drupal/info'.
  $mapping['mimetypes']['example_info'] = 'drupal/info';
  // Add new extension '.info' and map it to the 'drupal/info' MIME type.
  $mapping['extensions']['info'] = 'example_info';
  // Override existing extension mapping for '.ogg' files.
  $mapping['extensions']['ogg'] = 189;
}

Comments

Be vary careful when adding

Be vary careful when adding new entries. Since these mappings are numeric, you must ensure that you are not accidentally overwriting new entries. Here is the code we are using in the Media/File entity modules to add support for new mappings that will work with existing entries and not cause any regressions or data overwriting:

<?php
/**
* Implements hook_file_mimetype_mapping_alter().
*/
function mymodule_file_mimetype_mapping_alter(&$mapping) {
 
// Fix the mime type mapping for ogg.
 
$new_mappings['ogg'] = 'audio/ogg';

 
// Add support for m4v.
 
$new_mappings['m4v'] = 'video/x-m4v';

 
// Add support for mka and mkv.
 
$new_mappings['mka'] = 'audio/x-matroska';
 
$new_mappings['mkv'] = 'video/x-matroska';

  foreach (
$new_mappings as $extension => $mime_type) {
    if (!
in_array($mime_type, $mapping['mimetypes'])) {
     
// If the mime type does not already exist, add it.
     
$mapping['mimetypes'][] = $mime_type;
    }

   
// Get the index of the mime type and assign the extension to that key.
   
$index = array_search($mime_type, $mapping['mimetypes']);
   
$mapping['extensions'][$extension] = $index;
  }
}
?>

Login or register to post comments