![](/img/trans.png)
[英]How can I get the information of the file in a specific directory path such as file mime type and file name by php function?
[英]How can I get the mime type in PHP
我正在編寫腳本,我需要正確地獲取文件的mime類型(文件可以是任何類型)(我認為某些mime類型可能與其擴展名不同)。
使用中的網絡托管公司沒有mime_content_type()
,並且仍然(不知道他們將在哪一年進行修復)承諾修復PECL替代方案。
我可以采用其他哪種方式(而且我沒有訪問shell命令的權限)?
$ _FILES ['file'] ['type']來自上傳文件的瀏覽器,因此您完全不能依賴此值。
簽出finfo_file以根據文件內容識別文件類型。 該文件的擴展名也不可靠,因為用戶可以上傳帶有mp3擴展名的惡意代碼。
您可以嘗試finfo_file-它返回mime類型。
我使用以下函數,該函數是3種最常用方法的包裝:
function Mime($path, $magic = null)
{
$path = realpath($path);
if ($path !== false)
{
if (function_exists('finfo_open') === true)
{
$finfo = finfo_open(FILEINFO_MIME_TYPE, $magic);
if (is_resource($finfo) === true)
{
$result = finfo_file($finfo, $path);
}
finfo_close($finfo);
}
else if (function_exists('mime_content_type') === true)
{
$result = mime_content_type($path);
}
else if (function_exists('exif_imagetype') === true)
{
$result = image_type_to_mime_type(exif_imagetype($path));
}
return preg_replace('~^(.+);.+$~', '$1', $result);
}
return false;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.