如何从远程服务器使用file_get_contents后获取文件的mime类型

时间:2011-01-12 17:08:03

标签: php mime-types alfresco

我正在从Alfresco的php中读取一个文件,然后将其输出到浏览器。唯一的问题是mimetype或文件的扩展名。这是我正在使用的代码:

<?php
ob_start();
//require_once("libs/FirePHPCore/fb.php");
require_once("libs/AlfrescoConnect.php");

$nomeFile = rawurldecode($_GET['nomeFile']);    
$urlDownload = $_GET['urlDownload'];
$fileDownloadUrl = AlfrescoConnect::$serverPath. $urlDownload . "&attach=true&alf_ticket=".AlfrescoConnect::getTiket();
fb($fileDownloadUrl);


$cnt = file_get_contents($fileDownloadUrl);


header("Content-type: Application/octet-stream");
header('Cache-Control: must-revalidate');
header('Content-disposition: attachment; filename=' .$nomeFile);
echo($cnt);
exit();

echo("Impossibile trovare il file");

我从get becausa收到文件的名称我不知道如何从露天获取名称,但我必须以某种方式猜测mimetype。如果我在第一个字符中“回显”$ cnt,则会提到它是一个PDF(例如在屏幕上我看到 “%PDF-1.3%â€2 0 obj&lt;&lt; / Length 3 0 R / Filter / CCITTFaxDecode / DecodeParms&lt;&lt; / K 0 / Columns 2480 / Rows 3508&gt;&gt; / Type / XObject / Subtype / Image /宽度2480 /高度3508 / BitsPerComponent 1 / ColorSpace / DeviceGray&gt;&gt; stream“所以必须有一种方法可以通过函数从中获取mime_tipe。

感谢任何帮助!

编辑。如果有人是intereste这里是一个类,你可以用来从mime类型获得扩展。 http://www.ustrem.org/en/articles/mime-type-by-extension-en/

7 个答案:

答案 0 :(得分:4)

您可以使用finfo::buffer()方法:http://php.net/finfo_buffer

<?php
$finfo = new finfo(FILEINFO_MIME);
echo $finfo->buffer($cnt) . PHP_EOL;

注意:如果套件比使用面向对象的方法更好,你可以选择使用finfo_buffer程序功能。

答案 1 :(得分:3)

您不必猜测(也就是自动检测)MIME类型。

使用$http_response_header检索上次file_get_contents来电(或使用http:// wrapper的任何来电)的标头。

$contents = file_get_contents("https://www.example.com/");
$pattern = "/^content-type\s*:\s*(.*)$/i";
if (($header = preg_grep($pattern, $http_response_header)) &&
    (preg_match($pattern, array_shift(array_values($header)), $match) !== false))
{
    $content_type = $match[1];
    echo "Content-Type is '$content_type'\n";
}

答案 2 :(得分:2)

$http_response_header 之后解析 file_get_contents 对我来说非常不稳定。在某些情况下,当请求数量非常大时,我无法在标头中找到“Content-Type”。但他们在那里。

所以,我使用这样的解决方案:

$content = file_get_contents($url);
$fh = fopen('php://memory', 'w+b');
fwrite($fh, $content);

$contentType = mime_content_type($fh);

fclose($fh);

答案 3 :(得分:1)

使用cURL而不是file_get_contents,然后你可以看到响应头,希望它具有mime类型。

或者您可以尝试使用此http://www.php.net/manual/en/ref.fileinfo.php或已弃用的函数http://php.net/manual/en/function.mime-content-type.php

答案 4 :(得分:-1)

以下是Drupal中filefield_sources模块的curl实现。它可以在任何地方工作:

<?php
  // Inspect the remote image
  // Check the headers to make sure it exists and is within the allowed size.
  $ch = curl_init();
  curl_setopt($ch, CURLOPT_URL, $url);
  curl_setopt($ch, CURLOPT_HEADER, TRUE);
  curl_setopt($ch, CURLOPT_NOBODY, TRUE);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
  curl_setopt($ch, CURLOPT_HEADERFUNCTION, '_filefield_source_remote_parse_header');
  // Causes a warning if PHP safe mode is on.
  @curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
  curl_exec($ch);
  $info = curl_getinfo($ch);
  curl_close($ch);

/**
 * Parse cURL header and record the filename specified in Content-Disposition.
 */
function _filefield_source_remote_parse_header(&$ch, $header) {
  if (preg_match('/Content-Disposition:.*?filename="(.+?)"/', $header, $matches)) {
    // Content-Disposition: attachment; filename="FILE NAME HERE"
    _filefield_source_remote_filename($matches[1]);
  }
  elseif (preg_match('/Content-Disposition:.*?filename=([^; ]+)/', $header, $matches)) {
    // Content-Disposition: attachment; filename=file.ext
    _filefield_source_remote_filename($matches[1]);
  }

  // This is required by cURL.
  return strlen($header);
}

/**
 * Get/set the remote file name in a static variable.
 */
function _filefield_source_remote_filename($curl_filename = NULL) {
  static $filename = NULL;
  if (isset($curl_filename)) {
    $filename = $curl_filename;
  }
  return $filename;
}

 ?>

获取mime:

<?php
echo $info['content_type'];
?>

代码在这里:http://drupal.org/project/filefield_sources

答案 5 :(得分:-1)

把它放在课堂上:

/**
 * Given a string ($data) with a file's contents, guess and return the mime type
 *
 * Uses the standard unix program /usr/bin/file to handle the magic (pun intended)
 *
 * @param string $data
 */
public static function get_string_mime_type($data) {
    $file_cmd = '/usr/bin/file --brief --mime-type --no-buffer -';
    return rtrim(self::exec_write_read($file_cmd, $data));
}

/**
 * Executes $cmd, writes to $cmd's stdin, then returns what $cmd wrote to stdout
 */
private static function exec_write_read($cmd, $write, $log_errors = false) {
    $descriptorspec = array(
        0 => array("pipe", "r"),  // stdin is a pipe that $cmd will read from
        1 => array("pipe", "w"),  // stdout is a pipe that $cmd will write to
        2 => array("pipe", "w"),  // stderr is a pipe that $cmd will write to
    );

    $process = proc_open($cmd, $descriptorspec, $pipes);
    if (is_resource($process)) {
        // $pipes now looks like this:
        // 0 => writeable handle connected to child stdin
        // 1 => readable handle connected to child stdout
        // 2 => readable handle connected to child stderr

        fwrite($pipes[0], $write);
        fclose($pipes[0]);

        $output = stream_get_contents($pipes[1]);
        fclose($pipes[1]);

        if( $log_errors ){
            error_log(stream_get_contents($pipes[2]));
        }
        fclose($pipes[2]);

        // It is important that you close any pipes before calling
        // proc_close in order to avoid a deadlock
        $exit_code = proc_close($process);

        return $output;
    }
    else {
        throw new Exception("Couldn't open $cmd");
    }
}

答案 6 :(得分:-2)

小心!不仅要检查mimetype,还要检查恶意代码!!!!!!!!!

详情:PHP: How to get mimeType of a image with file_get_contents