2014-02-20 30 views
6

嗨我正在尋找最佳的方式來找出在任何本地文件或URL的MIME類型在PHP中。 我已經嘗試mime_content_type功能的PHP,但由於它已被棄用,我正在尋找更好的解決方案在PHP中的所有文件格式。找到MIME類型的文件或URL使用PHP的所有文件格式

mime_content_type — Detect MIME Content-type for a file ***(deprecated)*** 

我已經嘗試以下功能

echo 'welcome'; 
if (function_exists('finfo_open')) { 
    echo 'testing'; 
    $finfo = finfo_open(FILEINFO_MIME); 
    $mimetype = finfo_file($finfo, "http://4images.in/wp-content/uploads/2013/12/Siberian-Tiger-Running-Through-Snow-Tom-Brakefield-Getty-Images-200353826-001.jpg"); 
    finfo_close($finfo); 
    echo $mimetype; 
} 

上面的代碼是不適合我的工作,我只看到welcome爲output.I我不知道如果我錯在這裏做一些事情。


下面的代碼以某種方式在我的本地工作,但它不適用於網址。

$file = './apache_pb2.png'; 
$file_info = new finfo(FILEINFO_MIME); // object oriented approach! 
$mime_type = $file_info->buffer(file_get_contents($file)); // e.g. gives "image/jpeg" 
$mime = explode(';', $mime_type); 
print $mime[0]; 

有一些工作圍繞工作兩個(URL和本地的)。什麼是設置的所有內容(圖片,視頻,文件等)比PHP mime_content_type功能等MIME類型的最佳實踐。也建議在PHP中使用mime_content_type函數,它是最好的做法在PHP?

回答

5

找到了答案,

要查找的文件最好的方法的延伸,是利用path_info對本地文件和URL。 >See Example hereHere

//get the mime type for file 
$type = isset($this->mime_types[$ext]) ? $this->mime_types[$ext] : "application/octet-stream"; 

以上代碼同時適用於URL和本地文件 -

$info  = pathinfo($filename); 

$basename = $info['basename']; 

$ext  = $info['extension']; 

MIME類型

$mimeTypes = array("mp4" => "video/mp4");//創建一個數組。

注:

那些與CDN MP4視頻MIME類型的視頻/ MP4問題掙扎 - 我有 改變了我的class.s3.php文件中的變化 - 在MIME_TYPE []數組,也 >用putObject()函數進行交叉檢查。 MIME類型的

設置始終在編碼端,而不是在AWS S3 桶做,我們需要使用AWS PHP Class file or sdk做的MIME類型 操縱或使核心類 文件(如類進行必要的修改。 s3.php)

+2

好吧,你做了什麼,如果鏈接看起來像「https://avatars2.githubusercontent.com/u/124070?v=3&s=400」?沒有任何擴展! – alexglue

10

在PHP中使用file_info,使用FILEINFO_MIME_TYPE標誌作爲參數。

[實施例作爲它是從PHP手冊]

<?php 
$finfo = finfo_open(FILEINFO_MIME_TYPE); // return mime type ala mimetype extension 
foreach (glob("*") as $filename) { 
    echo finfo_file($finfo, $filename) . "\n"; 
} 
finfo_close($finfo); 
?> 

OUTPUT :

text/html 
image/gif 
application/vnd.ms-excel 

EDIT :

需要以啓用PHP.ini

;extension=php_fileinfo.dll 

延長從該行刪除分號,並重新啓動你的web服務器,你是好去。
Installation Doc.

+0

感謝您的快速回復:)我編輯了這個問題,我曾嘗試過相同的功能,但它沒有工作。我不知道爲什麼!沒有錯誤即將到來! @Shankar – Hitesh

+0

@hitesh檢查你有哪個版本的PHP –

+0

@hitesh,檢查編輯後的答案。 –

3
$type = image_type_to_mime_type(exif_imagetype($file)); 
+0

嗨感謝您的答案,但我想http://www.php.net/manual/en/function.image-type-to-mime-type.php [image_type_to_mime_type]和[exif_imagetype] [http:// www。 php.net/manual/en/function.exif-imagetype.php]只適用於不適用於其他文件(如視頻或文檔)的圖像。您有任何解決方案嗎? – Hitesh

+1

是的,你是對的。 – lbsweek

+0

嗯,我想這樣無論如何感謝您的答案!它至少對圖像有幫助:) – Hitesh

2

我試過上述所有這些解決方案後,就是我用什麼:

$command = "file -i {$filename}";

$mimeTypeArr = shell_exec($command);

該命令返回下面的一行:

filename: mime_type

我有這個之後,我爆炸並得到我所需要的。

$mimeTypeArr = shell_exec($command);

$mimeTypeArr = explode(':', $mimeTypeArr);

$mimeType = trim($mimeTypeArr[1]);

希望它能幫助!

+0

你可以使用'file -b -i'來避免解析:使用'-b'文件名不會被添加到輸出行。 –