mime-types deprecated php-5.5

mime types - ¿Cómo obtener el tipo MIME de un archivo en PHP 5.5?



mime-types deprecated (8)

Debe comprender que file_get_contents cargará todo el archivo a la memoria, no es una buena forma de obtener solo el tipo mime. No necesita usar el método de buffer y la función file_get_contents en este caso.

Para evitar errores y advertencias, es mejor que haga esto.

$filename = ''path to your file''; if (class_exists(''finfo'')) { $finfo = new finfo(FILEINFO_MIME_TYPE); if (is_object($finfo)) { echo $finfo->file($filename); } } else { echo ''fileinfo did not installed''; }

También debes saber que el archivo $ finfo-> lanzará PHP Warning si falla.

Si fileinfo no está instalado correctamente, y tiene una versión nueva de PHP, puede obtener el tipo MIME de los encabezados.

Puede usar cURL para obtener el tipo MIME de los encabezados.

$ch = curl_init(); curl_setopt_array($ch, array( CURLOPT_HEADER => true, CURLOPT_NOBODY => true, CURLOPT_RETURNTRANSFER => true, CURLOPT_SSL_VERIFYPEER => false, CURLOPT_SSL_VERIFYHOST => false, CURLOPT_FOLLOWLOCATION => true, CURLOPT_MAXREDIRS => 1, CURLOPT_URL => $link) ); $headers = curl_exec($ch); curl_close($ch); if (preg_match(''/Content-Type:/s(.*)/i'', $headers, $matches)) { echo trim($matches[1], "/t/n/r"); }else { echo ''There is no content type in the headers!''; }

También puede usar la función get_headers , pero es más lenta que la solicitud cURL.

$url = ''http://www.example.com''; $headers = get_headers($url, 1); echo $headers[''Content-Type''];

Estoy usando mime_content_type() en PHP 5.5 para obtener un tipo MIME, pero arroja fatal: error function not found .

¿Cómo puedo lograr esto en PHP 5.5?


Esta es la mejor solución que encontré al combinar dos publicaciones muy buenas

// Gracias a http://php.net/manual/en/function.mime-content-type.php#87856

function getMimeContentType($filename, $ext) { if(!function_exists(''mime_content_type'')) { if($mime_types = getMimeTypes()) { if (array_key_exists($ext, $mime_types)) { return $mime_types[$ext]; } elseif (function_exists(''finfo_open'')) { $finfo = finfo_open(FILEINFO_MIME); $mimetype = finfo_file($finfo, $filename); finfo_close($finfo); return $mimetype; } } return ''application/octet-stream''; } return mime_content_type($filename); }

// Gracias a http://php.net/manual/en/function.mime-content-type.php#107798

function getMimeTypes() { $url = ''http://svn.apache.org/repos/asf/httpd/httpd/trunk/docs/conf/mime.types''; $mimes = array(); foreach(@explode("/n",@file_get_contents($url)) as $x) { if(isset($x[0]) && $x[0]!==''#'' && preg_match_all(''#([^/s]+)#'', $x, $out) && isset($out[1]) && ($c = count($out[1])) > 1) { for($i=1; $i < $c; $i++) { $mimes[$out[1][$i]] = $out[1][0]; } } } return (@sort($mimes)) ? $mimes : false; }

Úselo enlace esto:

$filename = ''/path/to/the/file.pdf''; $ext = strtolower(array_pop(explode(''.'',$filename))); $content_type = getMimeContentType($filename, $ext);

Continuará funcionando incluso si la función mime_content_type ya no es compatible con php.


Haga uso de las funciones finfo() .

Una simple ilustración:

<?php $finfo = finfo_open(FILEINFO_MIME_TYPE); echo finfo_file($finfo, "path/to/image_dir/image.gif"); finfo_close($finfo);

OUTPUT :

image/gif

Nota: los usuarios de Windows deben incluir el archivo DLL php_fileinfo.dll incluido en php.ini para habilitar esta extensión.


He pasado demasiado tiempo intentando que las funciones finfo funcionen correctamente. Finalmente terminé creando mi propia función para unir la extensión de archivo a cualquier matriz de tipos de mime. No es una forma completa de asegurar que los archivos sean realmente lo que la extensión denota, pero ese problema puede ser mitigado por la forma en que procesa la E / S de dichos archivos en su servidor (es).

function mime_type($file) { // there''s a bug that doesn''t properly detect // the mime type of css files // https://bugs.php.net/bug.php?id=53035 // so the following is used, instead // src: http://www.freeformatter.com/mime-types-list.html#mime-types-list $mime_type = array( "3dml" => "text/vnd.in3d.3dml", "3g2" => "video/3gpp2", "3gp" => "video/3gpp", "7z" => "application/x-7z-compressed", "aab" => "application/x-authorware-bin", "aac" => "audio/x-aac", "aam" => "application/x-authorware-map", "aas" => "application/x-authorware-seg", "abw" => "application/x-abiword", "ac" => "application/pkix-attr-cert", "acc" => "application/vnd.americandynamics.acc", "ace" => "application/x-ace-compressed", "acu" => "application/vnd.acucobol", "adp" => "audio/adpcm", "aep" => "application/vnd.audiograph", "afp" => "application/vnd.ibm.modcap", "ahead" => "application/vnd.ahead.space", "ai" => "application/postscript", "aif" => "audio/x-aiff", "air" => "application/vnd.adobe.air-application-installer-package+zip", "ait" => "application/vnd.dvb.ait", "ami" => "application/vnd.amiga.ami", "apk" => "application/vnd.android.package-archive", "application" => "application/x-ms-application", // etc... // truncated due to ''s character limit in posts ); $extension = /strtolower(/pathinfo($file, /PATHINFO_EXTENSION)); if (isset($mime_type[$extension])) { return $mime_type[$extension]; } else { throw new /Exception("Unknown file type"); } }

Editar:

Me gustaría abordar el comentario de Davuz (ya que se sigue votando) y recordar a todos que puse en el pseudo descargo de responsabilidad en la parte superior que esto no es "prueba completa". Por lo tanto, tenga esto en cuenta al considerar el enfoque que he ofrecido en mi respuesta.


Obtenga el tamaño de la imagen usando:

$infFil=getimagesize($the_file_name);

y

echo $infFil["mime"]

getimagesize devuelve una matriz asociativa que tiene una clave MIME y, obviamente, el tamaño de la imagen también

Lo usé y funciona


Uso la herramienta MimeType desde Bat ( https://github.com/lingtalfi/Bat )

Utiliza el archivo de información si está disponible, y de manera predeterminada regresa a una asignación de "extensión => tipo de mímica".