상세 컨텐츠

본문 제목

PHP 지정된 파일의 mime 타입 알아내기

Web Development

by thankee 2008. 11. 16. 12:48

본문

mime_content_type

(PHP 4 >= 4.3.0, PHP 5)

string mime_content_type (string filename)
지정된 파일의 Mime Content Type을 반환합니다. 반환된 문자열은 text/plain 또는 application/octet-stream과 같은 MIME포멧입니다.

mime_content_type()을 사용한 예제소스

<?php
    echo mime_content_type('php.gif') . "\n";
    echo mime_content_type('test.php');
?>

결과는 다음과 같습니다.

image/gif
text/plain

아래는 사용자 코멘트

파일이름에 '+'문자가 포함되어 있으면 다음과 같은 경고를 내보내는 것 같습니다.(php 4.3)
    Warning: mime_magic: invalid mode 01002354664

모든 파일에 대해서 옳바른 Mime타입을 반환하지 않는 다는 것에 주의하세요. 예를들어 '.wmv'나 '.wma'는 바르게 인식 되지 않습니다.

제 MS windows환경에서는 다음과 같이 해야 mime_content_type함수를 사용할 수 있었습니다.
php.ini파일을 열고 mime_magic.debug라는 항목을 Off에서 On으로 변경
    [mime_magic]
    mime_magic.debug = On
    mime_magic.magicfile = "c:\php\extras\magic.mime"

이 함수는 windows에서도 동작합니다. 하지만 다음과 같은 사항을 php.ini파일을 열고 확인해보세요.
다음 라인이 주석해제 되어있는지 확인(다음 라인을 찾아서 앞에 세미콜론이 있다면 제거합니다.)
    extension=php_mime_magic.dll
php.ini파일의 아무 위치에 다음과 같은 라인을 확인하고 없으면 작성합니다.
    mime_magic.magicfile = "C:\php경로\magic.mime"

Linux 환경에서 mime_content_type를 사용할 수 없는 경우 때문에 다음과 같은 대체 함수를 사용합니다.
<?php
if (!function_exists('mime_content_type')) //해당 함수를 사용할 수 없다면
{
   function mime_content_type($f)  //이 대체함수를 사용
   {
      $f = escapeshellarg($f); 
      return trim( `file -bi $f` );
   }
}
?>

다음과 같은 대체 함수는 보안상 상당히 좋지않습니다. 왜냐하면, 업로드된 파일의 Mime 타입을 체크하여 실행파일이나 기타 원하지 않는 파일을 제거하고자 할 때 다음과 같은 mime_content_type체크 방법은 상당히 허술하기 때문입니다. '바이러스.exe.txt'와 같이 실행파일을 다른 파일로 속여서 업로드 한 뒤, 그 파일을 서버에서 실행할 수 도 있으며, php나 기타 코드 파일을 이미지파일로 속여서 업로드하여 코드를 실행 할 수 있기 때문입니다.
<?php
function mime_content_type_($filename)
{
    $mime = array
    (
        '.3dmf' => 'x-world/x-3dmf',
        '.a' => 'application/octet-stream',
        '.aab' => 'application/x-authorware-bin',
        //기타 자신이 원하는 확장자와 mime타입 기술
        '.xwd' => 'image/x-xwd',
        '.xyz' => 'chemical/x-pdb',
        '.z' => 'application/x-compressed',
        '.zip' => 'application/x-zip-compressed',
        '.zoo' => 'application/octet-stream',
        '.zsh' => 'text/x-script.zsh',
   );
   return $mime[strrchr($filename, '.')];
}
?>

출처 : php매뉴얼

번역 : thankee

관련글 더보기