2015-07-10 86 views
0

我試圖獲取MIME類型的配置文件圖片格式爲user_id.jpg或gif或png,我嘗試過使用此代碼,但它不起作用。獲取MIME類型的文件

function detectFileMimeType($filename='') 
{ 
    $filename = escapeshellcmd($filename); 
    $command = "file -b --mime-type -m /usr/share/misc/magic {$filename}"; 

    $mimeType = shell_exec($command); 

    return trim($mimeType); 
} 

function get_avatar($image, $user_id, $account) 
{ 
    $imgurl ="http://mypage/files/pictures/picture-" . ($user_id, $mimeType) . ".jpg"; 

    if (!is_imgurl_good($imgurl)) { 
    $imgurl = "http://mypage/sites/all/themes/simple_custom/user.png"; 
    } 
    return $imgurl; 
} 
+0

您是否考慮過[爲此設計的功能](http://php.net/manual/en/ref.fileinfo.php)? –

+0

我從您提供的頁面中獲取了該代碼。 – user123

+0

您從已棄用的'mime_content_type()'頁面中找到它。 –

回答

0

你應該能夠很容易得到MIME類型的文件的內置由PHP提供的功能 -

function detectFileMimeType($filename='') 
    $finfo = finfo_open(FILEINFO_MIME_TYPE); // return mime type 
    $fileglob = glob($filename); 
    echo finfo_file($finfo, $fileglob); 
    finfo_close($finfo); 
} 

http://php.net/manual/en/function.finfo-file.php

http://php.net/manual/en/function.glob.php

+0

我不知道如何將其結合到我現有的代碼..我需要擴展,現在它是硬編碼.jpg但一些用戶有GIF以及PNG – user123

0

除了finfo哪些工作正常,稍微簡單的方法是獲取PHP getimagesize函數返回,因爲這將返回從文件中提取的MIME類型:

$file = "blah/blahblah/bubbles.jpg"; 
$fileTypeData = getimagesize($file); 
$fileTypeData['mime'] = The Mime type of the image file.