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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1232769/
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-25 01:37:57  来源:igfitidea点击:

How to get the content-type of a file in PHP?

phpemailcontent-typefile-get-contents

提问by edt

I'm using PHP to send an email with an attachment. The attachment could be any of several different file types (pdf, txt, doc, swf, etc).

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

First, the script gets the file using "file_get_contents".

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

Later, the script echoes in the header:

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

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

How to I set the correct value for $the_content_type?

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

回答by deceze

I am using this function, which includes several fallbacks to compensate for older versions of PHP or simply bad results:

我正在使用这个函数,它包括几个回退来补偿旧版本的 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;
}

It tries to use the newer PHP finfofunctions. If those aren't available, it uses the mime_content_typealternative and includes the drop-in replacement from the Upgrade.phplibrary to make sure this exists. If those didn't return anything useful, it'll try the OS' filecommand. AFAIK that's only available on *NIX systems, you may want to change that or get rid of it if you plan to use this on Windows. If nothing worked, it tries exif_imagetypeas fallback for images only.

它尝试使用较新的 PHPfinfo函数。如果这些不可用,它会使用mime_content_type替代方案并包含Upgrade.php库中的替代方案以确保它存在。如果这些没有返回任何有用的东西,它会尝试操作系统的file命令。AFAIK 仅在 *NIX 系统上可用,如果您打算在 Windows 上使用它,您可能需要更改或摆脱它。如果没有任何效果,它exif_imagetype只会尝试作为图像的后备。

I have come to notice that different servers vary widely in their support for the mime type functions, and that the Upgrade.php mime_content_typereplacement is far from perfect. The limited exif_imagetypefunctions, both the original and the Upgrade.php replacement, are working pretty reliably though. If you're only concerned about images, you may only want to use this last one.

我注意到不同的服务器对 mime 类型函数的支持差异很大,并且 Upgrade.phpmime_content_type替代品远非完美。有限的exif_imagetype功能,无论是原始的还是 Upgrade.php 的替代品,都非常可靠地工作。如果您只关心图像,您可能只想使用最后一个。

回答by BoCyrill

It very easy to have it in php.

在 php 中使用它非常容易。

Simply call the following php function mime_content_type

只需调用以下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 documentation of the function mime_content_type()Hope it helps someone

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

回答by Quentin

With finfo_file: http://us2.php.net/manual/en/function.finfo-file.php

使用 finfo_file:http://us2.php.net/manual/en/function.finfo-file.php

回答by Richy B.

Here's an example using finfo_openwhich is available in PHP5 and PECL:

下面是一个使用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');
}

Alternatively, you can use the deprecatedmime_ content_ type function:

或者,您可以使用已弃用的mime_ content_ 类型函数:

$filetype=mime_content_type($tmpFileName);

or use the OS's in built functions:

或在内置函数中使用操作系统:

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

回答by George

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;
}

This worked for me

这对我有用

Why is mime_content_type() deprecated in PHP?

为什么在 PHP 中不推荐使用 mime_content_type()?

回答by user3348274

I guess that i found a short way. Get the image size using:

我想我找到了一条捷径。使用以下方法获取图像大小:

$infFil=getimagesize($the_file_name);

$infFil=getimagesize($the_file_name);

and

Content-Type: <?php echo $infFil["mime"] ?>; name="<?php echo $the_file_name; ?>"

The getimagesizereturns an associative array which have a MIME key

getimagesize返回其具有MIME密钥关联数组

I used it and it works

我用过它并且有效

回答by Martijn

I've tried most of the suggestions, but they all fail for me (I'm inbetween any usefull version of PHP apparantly. I ended up with the following function:

我已经尝试了大部分建议,但它们对我来说都失败了(我显然处于任何有用的 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;
}

回答by Eineki

There is the function header:

有函数头:

 header('Content-Type: '.$the_content_type);

Note that this function has to be called beforeany output. You can find further details in the reference http://php.net/header

请注意,必须任何输出之前调用此函数。您可以在参考http://php.net/header 中找到更多详细信息

Edit:

编辑:

Ops, I've misunderstood the question: Since php 4.0 there is the function mime_content_typeto detect the mimetype of a file.

操作,我误解了这个问题:从 php 4.0 开始,有函数mime_content_type来检测文件的 mimetype。

In php 5 is deprecated, should be replaced by the file infoset of functions.

在 php 5 中已弃用,应替换为文件信息函数集。

回答by Eineki

I really recommend using a Framework like "CodeIgniter" for seinding Emails. Here is a Screencast about "Sending Emails with CodeIgniter" in only 18 Minutes.

我真的建议使用像“CodeIgniter”这样的框架来发送电子邮件。这是一个关于“在 18 分钟内使用 CodeIgniter 发送电子邮件”的截屏视频。

http://net.tutsplus.com/videos/screencasts/codeigniter-from-scratch-day-3/

http://net.tutsplus.com/videos/screencasts/codeigniter-from-scratch-day-3/

回答by Jet

try this:

尝试这个:

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