2009-07-18 10 views
23

¿Existe un mapeo rápido y sucio de los tipos MIME a las extensiones en PHP que puedo utilizar?¿Cómo determino la (s) extensión (es) asociada (s) con un tipo MIME en PHP?

+0

Peo Por el simple hecho de querer asignar * extensiones * a * tipos MIME *, en lugar de al revés, debe tener en cuenta que ahora hay un soporte integrado para esto que deben aprovechar: vea [la respuesta de Jorge] (http: // stackoverflow.com/a/20494035/1709587) en lugar del aceptado. –

+1

@MarkAmery, sin embargo, como se indica, finfo_file() requiere que el archivo exista. Lo cual no siempre es el caso. La respuesta de Chaos es aún más en el punto del OP y sigue siendo válida 8 años después. – Wranorn

Respuesta

21

No incorporado, pero no es terriblemente difícil de rodar su propia:

function system_extension_mime_types() { 
    # Returns the system MIME type mapping of extensions to MIME types, as defined in /etc/mime.types. 
    $out = array(); 
    $file = fopen('/etc/mime.types', 'r'); 
    while(($line = fgets($file)) !== false) { 
     $line = trim(preg_replace('/#.*/', '', $line)); 
     if(!$line) 
      continue; 
     $parts = preg_split('/\s+/', $line); 
     if(count($parts) == 1) 
      continue; 
     $type = array_shift($parts); 
     foreach($parts as $part) 
      $out[$part] = $type; 
    } 
    fclose($file); 
    return $out; 
} 

function system_extension_mime_type($file) { 
    # Returns the system MIME type (as defined in /etc/mime.types) for the filename specified. 
    # 
    # $file - the filename to examine 
    static $types; 
    if(!isset($types)) 
     $types = system_extension_mime_types(); 
    $ext = pathinfo($file, PATHINFO_EXTENSION); 
    if(!$ext) 
     $ext = $file; 
    $ext = strtolower($ext); 
    return isset($types[$ext]) ? $types[$ext] : null; 
} 

function system_mime_type_extensions() { 
    # Returns the system MIME type mapping of MIME types to extensions, as defined in /etc/mime.types (considering the first 
    # extension listed to be canonical). 
    $out = array(); 
    $file = fopen('/etc/mime.types', 'r'); 
    while(($line = fgets($file)) !== false) { 
     $line = trim(preg_replace('/#.*/', '', $line)); 
     if(!$line) 
      continue; 
     $parts = preg_split('/\s+/', $line); 
     if(count($parts) == 1) 
      continue; 
     $type = array_shift($parts); 
     if(!isset($out[$type])) 
      $out[$type] = array_shift($parts); 
    } 
    fclose($file); 
    return $out; 
} 

function system_mime_type_extension($type) { 
    # Returns the canonical file extension for the MIME type specified, as defined in /etc/mime.types (considering the first 
    # extension listed to be canonical). 
    # 
    # $type - the MIME type 
    static $exts; 
    if(!isset($exts)) 
     $exts = system_mime_type_extensions(); 
    return isset($exts[$type]) ? $exts[$type] : null; 
} 
+5

Creo que esta es una respuesta antigua. Ahora debe usar 'fileinfo' http://www.php.net/manual/en/ref.fileinfo.php –

+6

@ JorgeB.G. Eso requiere que el archivo exista, ¿no es así? – danronmoon

+1

@danronmoon. si lo hace – Qix

2

Si desea utilizar un servicio web, que acabo de crear esto como parte de mi tipo MIME < -> icónico

http://stdicon.com/

Por ejemplo:

http://stdicon.com/ext/html

Se ejecuta en appengine por lo que debe tener alta disponibilidad.

+1

-1; no es necesario utilizar un servicio web para esto cuando se puede lograr localmente, no permite el mapeo de tipos MIME * a * extensiones (lo que el OP solicitó), y el servicio web tal como está actualmente carece de extensiones que mi local El archivo 'mime.types' en una instalación ordinaria de Ubuntu lo entiende, como' .woff'. –

+0

Navegar a http://stdicon.com genera un error para mí. Enlace a pastebin: http://pastebin.com/BjkGRv7H. Vale la pena señalar que el servicio en sí funciona bien sin embargo. – starbeamrainbowlabs

6

Puede usar mime_content_type pero está en desuso. fileinfo utilizar en su lugar:

function getMimeType($filename) { 
    $finfo = finfo_open(FILEINFO_MIME_TYPE); 
    $mime = finfo_file($finfo, $filename); 
    finfo_close($finfo); 
    return $mime; 
} 
+4

Vale la pena señalar que el OP realmente pidió mapear tipos MIME * a * extensiones de archivo. Esto todavía cubre el caso de uso más común (y probablemente el que el OP tuvo), así que ciertamente merece existir y lo he + 1ed, pero * no * es estrictamente una respuesta a la pregunta que se hizo pedante interpretado. –

+8

Nota: 'finfo_file()' y 'mime_content_type()' requiere que el archivo exista. – Pang

+2

¿Dónde dice que está en desuso? – Greg

2

Si está trabajando con variar las extensiones limitadas de imágenes y necesitan algo muy simple, creo que esto es suficiente.

switch($info['mime']) 
    { 
    case 'image/gif' : $extension = 'gif'; break; 
    case 'image/png' : $extension = 'png'; break; 
    case 'image/jpeg' : $extension = 'jpg'; break; 

    default : 
     throw new ApplicationException('The file uploaded was not a valid image file.'); 
    break; 
    } 
2

Es posible que desee utilizar esta biblioteca: el uso https://github.com/ralouphie/mimey

Ejemplo:

$mimes = new \Mimey\MimeTypes; 

// Convert extension to MIME type: 
$mimes->getMimeType('json'); // application/json 

// Convert MIME type to extension: 
$mimes->getExtension('application/json'); // json 

Esto porque al parecer la calidad de las funciones de PHP prestados es dudosa.

0

usan este archivo: https://github.com/ralouphie/mimey/blob/develop/mime.types.php

así:

$mimes=include('mime.types.php'); 

o copiar contenido:

$mime= array (
    'mimes' => 
    array (
    'ez' => 
    array (
     0 => 'application/andrew-inset', 
    ), 
    'aw' => 
    array (
     0 => 'application/applixware', 
    ), 
    'atom' => 
    array (
     0 => 'application/atom+xml', 
    ), 
    'atomcat' => 
    array (
     0 => 'application/atomcat+xml', 
    ) 

    ... 

y un ejemplo de conseguir de una corriente:

$finfo = new \finfo(FILEINFO_MIME_TYPE); 
$mime=$finfo->buffer($data); 
$mimes=include(__DIR__."/mime.types.php"); 
echo ($mime); //mime 
echo ($mimes['extensions'][$mime]); // file extension 
Cuestiones relacionadas