How to Detect File Types Without Relying on Extensions
Determining whether a file is an mp3 or image format beyond examining its extension is a valuable task in programming. Here's a comprehensive solution that doesn't rely on extensions:
PHP >= 5.3:
$mimetype = finfo_fopen(fopen($filename, 'r'), FILEINFO_MIME_TYPE);
PHP < 5.3:
$mimetype = mime_content_type($filename);
Alternatives:
Proxy Method:
For a more generalized approach, consider wrapping these functions into a proxy method:
function getMimeType($filename)
{
$mimetype = false;
if (function_exists('finfo_fopen')) {
// open with FileInfo
} elseif (function_exists('getimagesize')) {
// open with GD
} elseif (function_exists('exif_imagetype')) {
// open with EXIF
} elseif (function_exists('mime_content_type')) {
$mimetype = mime_content_type($filename);
}
return $mimetype;
}
By using this proxy method, you can easily determine the mimetype of a file based on the availability of different functions on your system.
免責聲明: 提供的所有資源部分來自互聯網,如果有侵犯您的版權或其他權益,請說明詳細緣由並提供版權或權益證明然後發到郵箱:[email protected] 我們會在第一時間內為您處理。
Copyright© 2022 湘ICP备2022001581号-3