Как получить тип mime файла после использования file_get_contents с удаленного сервера

Я читаю файл из php из Alfresco, а затем выводя его в браузер. Единственный ptoblem – это 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, я не знаю, как получить имя от alfresco, но я должен угадать mimetype каким-то образом. если i «echo» $ cnt в символах firsat есть ссылки на то, что это PDF (например, на экране я вижу «% PDF-1.3% âãÏÓ 2 0 obj << / Length 3 0 R / Filter / CCITTFaxDecode / DecodeParms << / K 0 / Columns 2480 / Строки 3508 >> / Тип / XObject / Подтип / Изображение / Ширина 2480 / Высота 3508 / BitsPerComponent 1 / ColorSpace / DeviceGray >> stream ", поэтому должен быть способ получить mime_tipe от него с функцией.

Любая помощь будет оценена!

Редактировать. Если кто-то заинтересован, вот класс, который вы можете использовать для получения расширения из mime-типа. http://www.ustrem.org/en/articles/mime-type-by-extension-en/

Используйте cURL вместо file_get_contents, тогда вы можете увидеть заголовок ответа, который, мы надеемся, будет иметь тип mime.

Или вы можете попробовать использовать этот http://www.php.net/manual/en/ref.fileinfo.php или эту устаревшую функцию http://php.net/manual/en/function.mime-content-type.php

Вы можете использовать метод finfo::buffer() : http://php.net/finfo_buffer .

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

ПРИМЕЧАНИЕ . Возможно, вы можете использовать процессуальную функцию finfo_buffer, если эти пакеты лучше, чем использование объектно-ориентированной методологии.

Вот реализация curl из модуля filefield_sources в Drupal. Возможно, он работает где угодно:

 <?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

Поместите это в класс:

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

БУДЬ ОСТОРОЖЕН ! НЕ ТОЛЬКО ПРОВЕРЬТЕ mimetype, но проверьте его на наличие вредоносного кода !!!!!!!!!

подробнее: PHP: Как получить mimeType изображения с файлом_get_contents