【问题标题】:How to get the content-type of a file in PHP?如何在 PHP 中获取文件的内容类型?
【发布时间】:2010-11-16 23:52:10
【问题描述】:

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

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

后来,脚本在头部回显:

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

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

【问题讨论】:

    标签: php email content-type file-get-contents


    【解决方案1】:

    【讨论】:

    • 在 PHP 中获取文件的 mime 类型在 a** 中仍然是一件很痛苦的事情 ... ;-)
    • 11 年过去了,还是很可怕
    【解决方案2】:

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

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

    【讨论】:

    • 是的,我计划将来使用它。感谢您的链接。
    【解决方案3】:

    这是一个使用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]);
    

    【讨论】:

    【解决方案4】:

    试试这个:

    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
    

    【讨论】:

      【解决方案5】:

      我正在使用这个函数,它包括几个后备来补偿旧版本的 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 系统上可用的 AFAIK,如果您打算在 Windows 上使用它,您可能想要更改或删除它。如果没有任何效果,它会尝试 exif_imagetype 仅作为图像的后备。

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

      【讨论】:

      • 回退到file 命令是多余的。 FileInfo 扩展(和 mime_content_type 函数)使用与file 命令相同的文件检测数据库。
      • @Sander 在我的测试中,我发现mime_content_type 有点不可靠,或者它的upgrade.php 替换可能是,而file 调用通常是成功的。我将不得不对此进行更多研究,以了解它在什么情况下何时以及为什么会失败。至少在那里并没有什么坏处。 :)
      • 我快速浏览了 mime_content_type 的 Upgrade.php 代码。首先它尝试 FileInfo PECL 扩展。如果不存在,它会尝试在 PHP 中自行解析 magic 文件。问题:它只在几个预定义的位置查找magic 文件。例如,它在我的 Debian Squeeze 上失败了。解析器也可能有错误,但我没有彻底检查。
      • @Sander 是的,我并不完全相信 upgrade.php 库的质量。因此,由于即使mime_content_type 似乎也并非无处不在,我认为回退到file 是合适的。 :)
      • 是的。最好只使用 FileInfo 并回退到 file
      【解决方案6】:
      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;
      }
      

      这对我有用

      Why is mime_content_type() deprecated in PHP?

      【讨论】:

        【解决方案7】:

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

        $infFil=getimagesize($the_file_name);

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

        getimagesize 返回一个具有 MIME 键的关联数组

        我用过,效果很好

        【讨论】:

          【解决方案8】:

          在 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 documentation of the function mime_content_type() 希望它可以帮助某人

          【讨论】:

            【解决方案9】:

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

            【讨论】:

              猜你喜欢
              • 2014-02-10
              • 2011-03-02
              • 1970-01-01
              • 2017-08-18
              • 1970-01-01
              • 2012-06-20
              • 1970-01-01
              • 2011-05-27
              • 2015-10-01
              相关资源
              最近更新 更多