简体   繁体   English

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

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

I'm using PHP to send an email with an attachment. 我正在使用PHP发送带有附件的电子邮件。 The attachment could be any of several different file types (pdf, txt, doc, swf, etc). 附件可以是几种不同的文件类型(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设置正确的值?

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 finfo functions. 它尝试使用较新的PHP finfo函数。 If those aren't available, it uses the mime_content_type alternative and includes the drop-in replacement from the Upgrade.php library to make sure this exists. 如果这些选项不可用,它将使用mime_content_type替代方法,并包括Upgrade.php库中的直接替换项,以确保它存在。 If those didn't return anything useful, it'll try the OS' file command. 如果没有返回任何有用的信息,它将尝试使用OS的file命令。 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. 仅在* NIX系统上可用的AFAIK,如果打算在Windows上使用它,则可能需要更改或取消该设置。 If nothing worked, it tries exif_imagetype as fallback for images only. 如果没有任何效果,它将尝试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_type replacement is far from perfect. 我已经注意到,不同的服务器在支持mime类型功能方面差异很大,并且Upgrade.php mime_content_type替换还远远不够完美。 The limited exif_imagetype functions, both the original and the Upgrade.php replacement, are working pretty reliably though. 有限的exif_imagetype函数(无论是原始函数还是Upgrade.php替换函数)都可以正常运行。 If you're only concerned about images, you may only want to use this last one. 如果您只关心图像,则可能只想使用最后一个。

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文档希望对您有所帮助

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

Here's an example using finfo_open which 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 deprecated mime_ 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]);
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()?

I guess that i found a short way. 我想我找到了很短的路。 Get the image size using: 使用以下方法获取图像大小:

$infFil=getimagesize($the_file_name);

and

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

The getimagesize returns an associative array which have a MIME key getimagesize返回具有MIME密钥的关联数组

I used it and it works 我用它并且有效

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

There is the function header: 有函数头:

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

Note that this function has to be called before any 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_type to detect the mimetype of a file. 操作,我误解了这个问题:自php 4.0起,有mime_content_type函数可检测文件的mimetype。

In php 5 is deprecated, should be replaced by the file info set of functions. 在php 5中已弃用,应由功能的文件信息集代替。

I really recommend using a Framework like "CodeIgniter" for seinding Emails. 我真的建议使用“ CodeIgniter”之类的框架来查找电子邮件。 Here is a Screencast about "Sending Emails with CodeIgniter" in only 18 Minutes. 这是有关仅用18分钟即可发送“使用CodeIgniter发送电子邮件”的截屏视频。

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM