php 如何使用php找到文件的mime类型?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/134833/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 21:36:17  来源:igfitidea点击:

How do I find the mime-type of a file with php?

phpfilesystemshttp-headerscontent-type

提问by Issac Kelly

Ok, so I have an index.php file which has to process many different file types. how do I guess the filetype based on the REQUEST_URI.

好的,所以我有一个 index.php 文件,它必须处理许多不同的文件类型。我如何根据REQUEST_URI.

If I request http://site/image.jpg, and all requests redirect through index.php, which looks like this

如果我请求http://site/image.jpg,并且所有请求都通过 index.php 重定向,如下所示

<?php
   include('/www/site'.$_SERVER['REQUEST_URI']);
?>

How would I make that work correctly?

我将如何使其正常工作?

Should I test based on the extension of the file requested, or is there a way to get the filetype?

我应该根据请求的文件的扩展名进行测试,还是有办法获取文件类型?

回答by leek

If you are sure you're only ever working with images, you can check out the getimagesize()exif_imagetype()PHP function, which attempts to return the image mime-type.

如果您确定您只使用过图像,则可以查看 获取图像大小()exif_imagetype()PHP 函数,它尝试返回图像 MIME 类型。

If you don't mind external dependencies, you can also check out the excellent getID3library which can determine the mime-type of many different file types.

如果你不介意外部依赖,你还可以查看优秀的getID3库,它可以确定许多不同文件类型的 MIME 类型。

Lastly, you can check out the mime_content_type()function - but it has been deprecated for the FileinfoPECL extension.

最后,您可以查看mime_content_type()函数 - 但它已被FileinfoPECL 扩展弃用。

回答by Eric_WVGG

mime_content_type() is deprecated, so you won't be able to count on it working in the future. There is a "fileinfo" PECL extension, but I haven't heard good things about it.

mime_content_type() 已被弃用,因此您将无法指望它在未来工作。有一个“fileinfo”PECL 扩展名,但我还没有听说过关于它的好消息。

If you are running on a *nix server, you can do the following, which has worked fine for me:

如果您在 *nix 服务器上运行,则可以执行以下操作,这对我来说效果很好:

$file = escapeshellarg( $filename );
$mime = shell_exec("file -bi " . $file);
$filename should probably include the absolute path.

回答by Ale

function get_mime($file) {
  if (function_exists("finfo_file")) {
    $finfo = finfo_open(FILEINFO_MIME_TYPE); // return mime type ala mimetype extension
    $mime = finfo_file($finfo, $file);
    finfo_close($finfo);
    return $mime;
  } else if (function_exists("mime_content_type")) {
    return mime_content_type($file);
  } else if (!stristr(ini_get("disable_functions"), "shell_exec")) {
    // http://stackoverflow.com/a/134930/1593459
    $file = escapeshellarg($file);
    $mime = shell_exec("file -bi " . $file);
    return $mime;
  } else {
    return false;
  }
}

For me, nothing of this does work - mime_content_typeis deprecated, finfois not installed, and shell_execis not allowed.

对我来说,这一切都不起作用 -mime_content_type已弃用、finfo未安装且shell_exec不允许使用。

回答by Shane

I actually got fed up by the lack of standardMIME sniffing methods in PHP. Install fileinfo... Use deprecated functions... Oh these work, but only for images! I got fed up of it, so I did some research and found the WHATWG Mimesniffing spec- I believe this is still a draft spec though.

我实际上对 PHP 中缺乏标准的MIME 嗅探方法感到厌烦。安装文件信息...使用不推荐使用的功能...哦,这些工作,但仅适用于图像!我受够了,所以我做了一些研究并找到了WHATWG Mimesniffing 规范——不过我相信这仍然是一个草案规范。

Anyway, using this specification, I was able to implement a mimesniffer in PHP. Performance is not an issue. In fact on my humble machine, I was able to open and sniff thousands of files before PHP timed out.

不管怎样,使用这个规范,我能够在 PHP 中实现一个 mimesniffer。性能不是问题。事实上,在我不起眼的机器上,我能够在 PHP 超时之前打开和嗅探数千个文件。

Here is the MimeReader class.

这是MimeReader 类

require_once("MimeReader.php");

$mime = new MimeReader(<YOUR FILE PATH>);
$mime_type_string = $mime->getType();     // "image/jpeg" etc.

回答by Andrew

If you are working with Images only and you need mime type (e.g. for headers), then this is the fastest and most direct answer:

如果您只使用图像并且需要 MIME 类型(例如标题),那么这是最快和最直接的答案:

$file = 'path/to/image.jpg';
$image_mime = image_type_to_mime_type(exif_imagetype($file));

It will output true image mime type even if you rename your image file

即使您重命名图像文件,它也会输出真实的图像 MIME 类型

回答by Devon

According to the php manual, the finfo-filefunction is best way to do this. However, you will need to install the FileInfoPECL extension.

根据 php 手册,finfo-file函数是最好的方法。但是,您需要安装FileInfoPECL 扩展。

If the extension is not an option, you can use the outdated mime_content_typefunction.

如果扩展名不是一个选项,您可以使用过时的mime_content_type函数。

回答by David

mime_content_type()appears to be the way to go, notwithstanding the above comments saying it is deprecated. It is not -- or at least this incarnation of mime_content_type()is not deprecated, according to http://php.net/manual/en/function.mime-content-type.php. It is part of the FileInfo extension, but the PHP documentation now tells us it is enabled by default as of PHP 5.3.0.

mime_content_type()似乎是要走的路,尽管上面的评论说它已被弃用。mime_content_type()根据http://php.net/manual/en/function.mime-content-type.php 的说法,它不是 - 或者至少这种化身没有被弃用。它是 FileInfo 扩展的一部分,但 PHP 文档现在告诉我们它从 PHP 5.3.0 开始默认启用。

回答by jhaagsma

You can use finfo to accomplish this as of PHP 5.3:

从 PHP 5.3 开始,您可以使用 finfo 来完成此操作:

<?php
$info = new finfo(FILEINFO_MIME_TYPE);
echo $info->file('myImage.jpg');
// prints "image/jpeg"

The FILEINFO_MIME_TYPE flag is optional; without it you get a more verbose string for some files; (apparently some image types will return size and colour depth information). Using the FILEINFO_MIME flag returns the mime-type and encoding if available (e.g. image/png; charset=binary or text/x-php; charset=us-ascii). See this sitefor more info.

FILEINFO_MIME_TYPE 标志是可选的;没有它,你会得到一些文件的更详细的字符串;(显然某些图像类型会返回大小和颜色深度信息)。如果可用,使用 FILEINFO_MIME 标志返回 mime 类型和编码(例如 image/png;charset=binary 或 text/x-php;charset=us-ascii)。有关更多信息,请参阅此站点

回答by Joshua

The mime of any file on your server can be gotten with this

你的服务器上任何文件的 mime 都可以用这个来获取

<?php
function get_mime($file_path){
  $finfo = new finfo(FILEINFO_MIME_TYPE);
  $type  = $finfo->file(file_path);
}

$mime = get_mime('path/to/file.ext');

回答by Klemen Tu?ar

If you run Linux and have the extension you could simply read the MIME type from /etc/mime.types by making a hash array. You can then store that in memory and simply call the MIME by array key :)

如果您运行 Linux 并具有扩展名,您可以通过创建散列数组从 /etc/mime.types 中简单地读取 MIME 类型。然后您可以将其存储在内存中,只需通过数组键调用 MIME :)

/**
 * Helper function to extract all mime types from the default Linux /etc/mime.types
 */
function get_mime_types() {
    $mime_types = array();
    if (
        file_exists('/etc/mime.types') &&
        ($fh = fopen('/etc/mime.types', 'r')) !== false
    ) {
        while (($line = fgets($fh)) !== false) {
            if (!trim($line) || substr($line, 0, 1) === '#') continue;
            $mime_type = preg_split('/\t+/', rtrim($line));
            if (
                is_array($mime_type) &&
                isset($mime_type[0]) && $mime_type[0] &&
                isset($mime_type[1]) && $mime_type[1]
            ) {
                foreach (explode(' ', $mime_type[1]) as $ext) {
                    $mime_types[$ext] = $mime_type[0];
                }
            }
        }
        fclose($fh);
    }
    return $mime_types;
}