如何在PHP中获取文件的内容类型?

24

我正在使用PHP发送带有附件的电子邮件。附件可能是多种不同的文件类型(pdf,txt,doc,swf等)。

首先,脚本使用“file_get_contents”获取文件。

稍后,脚本在标题中回显:

Content-Type: <?php echo $the_content_type; ?>; name="<?php echo $the_file_name; ?>"

如何为$the_content_type设置正确的值?

10个回答

29

我正在使用这个函数,它包括多种fallback处理方式以应对旧版本的PHP或简单的错误结果:

function getFileMimeType($file) {
    if (function_exists('finfo_file')) {
        $finfo = finfo_open(FILEINFO_MIME_TYPE);
        $type = finfo_file($finfo, $file);
        finfo_close($finfo);
    } else {
        require_once 'upgradephp/ext/mime.php';
        $type = mime_content_type($file);
    }

    if (!$type || in_array($type, array('application/octet-stream', 'text/plain'))) {
        $secondOpinion = exec('file -b --mime-type ' . escapeshellarg($file), $foo, $returnCode);
        if ($returnCode === 0 && $secondOpinion) {
            $type = $secondOpinion;
        }
    }

    if (!$type || in_array($type, array('application/octet-stream', 'text/plain'))) {
        require_once 'upgradephp/ext/mime.php';
        $exifImageType = exif_imagetype($file);
        if ($exifImageType !== false) {
            $type = image_type_to_mime_type($exifImageType);
        }
    }

    return $type;
}

该代码尝试使用更新的PHP finfo函数。如果这些函数不可用,它会使用mime_content_type替代方案,并包含Upgrade.php库中的插件以确保存在该替代方案。如果这些方法都没有返回有用的信息,它将尝试使用操作系统的file命令。据我所知,在*NIX系统上才有此功能,如果您计划在Windows上使用此功能,您可能需要更改它或将其删除。如果什么都不起作用,它将尝试使用exif_imagetype作为图像的后备方案。

我已经注意到不同的服务器对mime类型函数的支持差别很大,并且Upgrade.php的mime_content_type替代方案远非完美。受限的exif_imagetype函数,无论是原始的还是Upgrade.php替代方案,都表现得相当可靠。如果您只关心图像,则可能只想使用最后一个函数。


file 命令的回退是多余的。FileInfo 扩展(以及 mime_content_type 函数)使用与 file 命令相同的文件检测数据库。 - Sander Marechal
@Sander 在我的测试中,我发现 mime_content_type 有些不可靠,或者可能是它的 upgrade.php 替代品有问题,而 file 调用通常是成功的。我需要更深入地研究一下,在什么情况下以及为什么会失败。至少它在那里不会造成任何伤害。 :) - deceze
我快速查看了Upgrade.php代码中的mime_content_type部分。首先它会尝试使用FileInfo PECL扩展。如果不存在,它会在PHP中自己解析magic文件。问题是:它只会在一些预定义的位置查找magic文件。例如,在我的Debian Squeeze上失败了。也有可能解析器存在漏洞,但我没有仔细检查。 - Sander Marechal
@Sander 是的,我并不完全相信 upgrade.php 库的质量。因此,既然连 mime_content_type 似乎也不是到处都可用,我认为回退到 file 是合适的。 :) - deceze
是的。最好只使用FileInfo并回退到“file”。 - Sander Marechal
当仅检测图像类型时,我认为仅使用 exif_imagetype 是最好的方法。我尝试使用 finfo_file,它在大多数情况下运行良好,但有时会返回类型为 application/octet-stream 而不是正确的文件类型。 - Nate

12

在PHP中很容易实现。

只需调用以下PHP函数mime_content_type即可。

<?php
    $filelink= 'uploads/some_file.pdf';
    $the_content_type = "";

    // check if the file exist before
    if(is_file($file_link)) {
        $the_content_type = mime_content_type($file_link);
    }
    // You can now use it here.

?>

PHP函数mime_content_type()的文档 希望对某人有所帮助


7

8
在PHP中获取文件的MIME类型仍然非常麻烦...;-) - Philippe Gerber
1
11年过去了,它仍然很糟糕。 - Sliq

4

下面是一个使用 finfo_open 的示例,该函数可用于 PHP5 和 PECL:

$mimepath='/usr/share/magic'; // may differ depending on your machine
// try /usr/share/file/magic if it doesn't work
$mime = finfo_open(FILEINFO_MIME,$mimepath);
if ($mime===FALSE) {
 throw new Exception('Unable to open finfo');
}
$filetype = finfo_file($mime,$tmpFileName);
finfo_close($mime);
if ($filetype===FALSE) {
 throw new Exception('Unable to recognise filetype');
}

或者,您可以使用已弃用的 mime_content_type 函数:

$filetype=mime_content_type($tmpFileName);

或者使用操作系统内置的函数:

ob_start();
system('/usr/bin/file -i -b ' . realpath($tmpFileName));
$type = ob_get_clean();
$parts = explode(';', $type);
$filetype=trim($parts[0]);

3
mime_content_type 函数并未被弃用。 - Andrew Lalis
真 - 原来手册上标记为弃用是错误的(https://bugs.php.net/bug.php?id=71367和https://dev59.com/4nM_5IYBdhLWcg3wslfs#39676272) - Richy B.

3
function getMimeType( $filename ) {
        $realpath = realpath( $filename );
        if ( $realpath
                && function_exists( 'finfo_file' )
                && function_exists( 'finfo_open' )
                && defined( 'FILEINFO_MIME_TYPE' )
        ) {
                // Use the Fileinfo PECL extension (PHP 5.3+)
                return finfo_file( finfo_open( FILEINFO_MIME_TYPE ), $realpath );
        }
        if ( function_exists( 'mime_content_type' ) ) {
                // Deprecated in PHP 5.3
                return mime_content_type( $realpath );
        }
        return false;
}

这对我有用

为什么PHP中的mime_content_type()被弃用了?


2

我猜我找到了一种简便的方法。使用以下代码获取图像大小:

$infFil = getimagesize($the_file_name);

以及

Content-Type: <?php echo $infFil["mime"] ?>; name="<?php echo $the_file_name; ?>"
getimagesize 返回一个关联数组,其中包含 MIME 键。
我使用它,它有效。

0

我尝试了大部分的建议,但它们对我都无效(显然我处于任何有用版本的PHP之间)。最终我得到了以下函数:

function getShellFileMimetype($file) {
    $type = shell_exec('file -i -b '. escapeshellcmd( realpath($_SERVER['DOCUMENT_ROOT'].$file)) );
    if( strpos($type, ";")!==false ){
        $type = current(explode(";", $type));
    }
    return $type;
}

0
  • 从字符串: $mediaType = (new \finfo(FILEINFO_MIME))->buffer($string)
  • 从文件名: $mediaType = (new \finfo(FILEINFO_MIME))->file($filename)

PHP需要安装ext-fileinfo模块(通常已预安装)。

FILEINFO_MIME - 返回RFC 2045定义的MIME类型和MIME编码。

如果您使用composer,请不要忘记将ext-fileinfo条目添加到composer.json中。

文档:https://www.php.net/manual/en/ref.fileinfo.php


-3

试试这个:

function ftype($f) {
                    curl_setopt_array(($c = @curl_init((!preg_match("/[a-z]+:\/{2}(?:www\.)?/i",$f) ? sprintf("%s://%s/%s", "http" , $_SERVER['HTTP_HOST'],$f) :  $f))), array(CURLOPT_RETURNTRANSFER => 1, CURLOPT_HEADER => 1));
                        return(preg_match("/Type:\s*(?<mime_type>[^\n]+)/i", @curl_exec($c), $m) && curl_getinfo($c, CURLINFO_HTTP_CODE) != 404)  ? ($m["mime_type"]) : 0;

         }
echo ftype("http://img2.orkut.com/images/medium/1283204135/604747203/ln.jpg"); // print image/jpeg

-3

是的,我计划在未来使用它。谢谢提供链接。 - edt

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接