string mime_content_type ( string $filename )
(PHP 4 >= 4.3.0, PHP 5)

이 함수는 파일의 확장자를 이용해 파일의 Type을 출력합니다.

예로 myimage.bmp가 있다고 가정하면 실제 Type 은 jpg 이지만 확장자가 bmp 인 결과 값을 출력합니다.

<?php
 function user_mime_content_type($filename)
 {
   if(!function_exists('mime_content_type'))
   {
      $type = array(
      'txt' => 'text/plain',
      'htm' => 'text/html',
      'html' => 'text/html',
      'php' => 'text/html',
      'css' => 'text/css',
      'js' => 'application/javascript',
      'json' => 'application/json',
      'xml' => 'application/xml',
      'swf' => 'application/x-shockwave-flash',
      'flv' => 'video/x-flv',

      // images
      'png' => 'image/png',
      'jpe' => 'image/jpeg',
      'jpeg' => 'image/jpeg',
      'jpg' => 'image/jpeg',
      'gif' => 'image/gif',
      'bmp' => 'image/bmp',
      'ico' => 'image/vnd.microsoft.icon',
      'tiff' => 'image/tiff',
      'tif' => 'image/tiff',
      'svg' => 'image/svg+xml',
      'svgz' => 'image/svg+xml',
     
      // archives
      'zip' => 'application/zip',
      'rar' => 'application/x-rar-compressed',
      'exe' => 'application/x-msdownload',
      'msi' => 'application/x-msdownload',
      'cab' => 'application/vnd.ms-cab-compressed',
     
      // audio/video
      'mp3' => 'audio/mpeg',
      'qt' => 'video/quicktime',
       'mov' => 'video/quicktime',
    
      // adobe
      'pdf' => 'application/pdf',
      'psd' => 'image/vnd.adobe.photoshop',
      'ai' => 'application/postscript',
      'eps' => 'application/postscript',
      'ps' => 'application/postscript',

      // ms office
      'doc' => 'application/msword',
      'rtf' => 'application/rtf',
      'xls' => 'application/vnd.ms-excel',
      'ppt' => 'application/vnd.ms-powerpoint',
    
      // open office
      'odt'=>'application/vnd.oasis.opendocument.text',
      'ods'=>'application/vnd.oasis.opendocument.spreadsheet',
     );
     $ext = strtolower(array_pop(explode('.',$filename)));
     if (array_key_exists($ext, $type))
     {
         return $type[$ext];
      }
      elseif (function_exists('finfo_open'))
     {
         $finfo = finfo_open(FILEINFO_MIME);
         $mimetype = finfo_file($finfo, $filename);
         finfo_close($finfo);
         return $mimetype;
     }
     else
    {
        return 'application/octet-stream';
    }
  }
  else
  {
      return mime_content_type($filename);
   }
 }
 ?>

일부 서버가 mime_content_type 함수를 지원하지 않을 때 위와 같이 사용자 함수를 만들어 사용할 수 있습니다.

<?php
 $type = user_mime_content_type("test.bmp.txt.zip.jpg");
 print_r($type); 
 // 결과: image/jpeg
 ?>

<?php
 $type = user_mime_content_type("test.jpg");
 header("Content-type: ".$type);
 header("content-disposition: attachment; filename=\"test.jpg\"");
 header("content-description: php generated data");
 header("Pragma: no-cache"); 
 header("Expires: 0"); 

 $fp = fopen("test.jpg", "r");
 if (!fpassthru($fp))
 {
   fclose($fp);
 }
 @flush();
 ?>

0 댓글