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

问题描述 投票:5回答:6

我正在从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%âÏÓ20 ob​​j << / Length 3 0 R / Filter / CCITTFaxDecode / DecodeParms << / K 0 / Columns 2480 / Rows 3508 >> / Type / XObject / Subtype / Image / Width 2480 / Height 3508 / BitsPerComponent 1 / ColorSpace / DeviceGray >> stream“所以必须有办法获取mime_tipe从它有一个功能。

任何帮助表示赞赏!

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

php mime-types alfresco
6个回答
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


5
投票

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

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

注意:如果套件比使用面向对象的方法更好,则可以选择使用finfo_buffer过程函数。


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

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

 ?>

得到哑剧:

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

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


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

-2
投票

小心 !不仅要检查mimetype,还要检查恶意代码!!!!!!!!! 细节:PHP: How to get mimeType of a image with file_get_contents

© www.soinside.com 2019 - 2024. All rights reserved.