简体   繁体   中英

create a file (name.extension) by mime type

How to create a file (name_of_file . file_extension), by mime type? The list of mimes is dynamic.

Example:

MIME                   Extension
application/msword  |  .doc
text/plain          |  .txt
text/css            |  .css

I dont wanna use array("mime" => "extension");

I have the mime type, but i need the file extension.

To avoid using a lookup table (at least avoid you having to define one) you can use finfo_file .

echo finfo_file('myfile.jpg', finfo_open(FILEINFO_MIME_TYPE)); // output: image/jpg

If you're on 5.0, you may try mime_content_type (But keep in mind this is deprecated, so if you're looking for upgrade-compatible, you may want to default to the new finfo_file when possible):

echo mime_content_type('myfile.jpg'); // output: image/jpg

// When possible, it will use upgraded finfo_file, but will default back
// to content_mime_type when necessary
function getMimeType($file){
  if (function_exists('finfo_file') && defined('FILEINFO_MIME_TYPE')){
    $return_mime = finfo_open(FILEINFO_MIME_TYPE);
    return finfo_file($file, $return_mime);
  }
  return content_mime_type($file);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM