问题
I am writing a script and I need to correctly (I think some mime types can be different from their extensions) get the mime types of files (the files can be of any type).
Web hosting company in use does not have mime_content_type()
and is still (don't know which year they will be fixing it) promising to fix the PECL alternative.
Which other way can I go about it (and I don;t have access to shell commands)?
回答1:
You could try finfo_file - it returns the mime type.
http://php.net/manual/en/book.fileinfo.php
回答2:
I use the following function, which is a wrapper for the 3 most common methods:
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;
}
回答3:
$_FILES['file']['type'] comes from the browser that uploads the file so you can't rely on this value at all.
Check out finfo_file for identifying file types based on file content. The extension of the file is also unreliable as the user could upload malicious code with an mp3 extension.
来源:https://stackoverflow.com/questions/3693245/how-can-i-get-the-mime-type-in-php