mail create and php email content-type file-get-contents

create - ¿Cómo obtener el tipo de contenido de un archivo en PHP?



phpmailer install (10)

Estoy usando PHP para enviar un correo electrónico con un archivo adjunto. El archivo adjunto puede ser cualquiera de varios tipos de archivos diferentes (pdf, txt, doc, swf, etc.).

Primero, el script obtiene el archivo usando "file_get_contents".

Más tarde, el script se hace eco en el encabezado:

Content-Type: <?php echo $the_content_type; ?>; name="<?php echo $the_file_name; ?>"

¿Cómo establezco el valor correcto para $ the_content_type ?


Ahí está el encabezado de la función:

header(''Content-Type: ''.$the_content_type);

Tenga en cuenta que esta función debe llamarse antes de cualquier salida. Puede encontrar más detalles en la referencia http://php.net/header

Editar:

Ops, he entendido mal la pregunta: desde php 4.0 existe la función mime_content_type para detectar el tipo MIME de un archivo.

En PHP 5 está en desuso, debe ser reemplazado por el conjunto de funciones de información de archivos .


Aquí hay un ejemplo usando finfo_open que está disponible en PHP5 y PECL:

$mimepath=''/usr/share/magic''; // may differ depending on your machine // try /usr/share/file/magic if it doesn''t work $mime = finfo_open(FILEINFO_MIME,$mimepath); if ($mime===FALSE) { throw new Exception(''Unable to open finfo''); } $filetype = finfo_file($mime,$tmpFileName); finfo_close($mime); if ($filetype===FALSE) { throw new Exception(''Unable to recognise filetype''); }

Alternativamente, puede usar la función mime_ content_ type en desuso :

$filetype=mime_content_type($tmpFileName);

o utilizar el sistema operativo en funciones integradas:

ob_start(); system(''/usr/bin/file -i -b '' . realpath($tmpFileName)); $type = ob_get_clean(); $parts = explode('';'', $type); $filetype=trim($parts[0]);



Es muy fácil tenerlo en php.

Simplemente llame a la siguiente función php mime_content_type

<?php $filelink= ''uploads/some_file.pdf''; $the_content_type = ""; // check if the file exist before if(is_file($file_link)) { $the_content_type = mime_content_type($file_link); } // You can now use it here. ?>

Documentación PHP de la función mime_content_type () Espero que ayude a alguien


Estoy usando esta función, que incluye varias alternativas para compensar las versiones anteriores de PHP o simplemente los malos resultados:

function getFileMimeType($file) { if (function_exists(''finfo_file'')) { $finfo = finfo_open(FILEINFO_MIME_TYPE); $type = finfo_file($finfo, $file); finfo_close($finfo); } else { require_once ''upgradephp/ext/mime.php''; $type = mime_content_type($file); } if (!$type || in_array($type, array(''application/octet-stream'', ''text/plain''))) { $secondOpinion = exec(''file -b --mime-type '' . escapeshellarg($file), $foo, $returnCode); if ($returnCode === 0 && $secondOpinion) { $type = $secondOpinion; } } if (!$type || in_array($type, array(''application/octet-stream'', ''text/plain''))) { require_once ''upgradephp/ext/mime.php''; $exifImageType = exif_imagetype($file); if ($exifImageType !== false) { $type = image_type_to_mime_type($exifImageType); } } return $type; }

Intenta usar las nuevas funciones de PHP finfo . Si no están disponibles, utiliza la alternativa mime_content_type e incluye el reemplazo Upgrade.php biblioteca Upgrade.php para asegurarse de que existe. Si esos no devolvieron nada útil, intentará con el comando de file del sistema operativo. AFAIK que solo está disponible en los sistemas * NIX, es posible que desee cambiarlo o deshacerse de él si planea usarlo en Windows. Si nada funcionó, intenta exif_imagetype como exif_imagetype para imágenes solamente.

Me he dado cuenta de que los diferentes servidores varían ampliamente en su compatibilidad con las funciones de tipo mime, y que el reemplazo de Upgrade.php mime_content_type está lejos de ser perfecto. Sin exif_imagetype , las funciones limitadas exif_imagetype , tanto las originales como las de Upgrade.php, están funcionando de manera bastante confiable. Si solo te preocupan las imágenes, es posible que solo quieras utilizar esta última.


He intentado la mayoría de las sugerencias, pero todas fallan para mí (estoy en medio de cualquier versión útil de PHP aparentemente. Terminé con la siguiente función:

function getShellFileMimetype($file) { $type = shell_exec(''file -i -b ''. escapeshellcmd( realpath($_SERVER[''DOCUMENT_ROOT''].$file)) ); if( strpos($type, ";")!==false ){ $type = current(explode(";", $type)); } return $type; }



Supongo que encontré un camino corto. Obtenga el tamaño de la imagen usando:

$infFil=getimagesize($the_file_name);

y

Content-Type: <?php echo $infFil["mime"] ?>; name="<?php echo $the_file_name; ?>"

El getimagesize devuelve una matriz asociativa que tiene una clave MIME

Lo usé y funciona


prueba esto:

function ftype($f) { curl_setopt_array(($c = @curl_init((!preg_match("/[a-z]+://{2}(?:www/.)?/i",$f) ? sprintf("%s://%s/%s", "http" , $_SERVER[''HTTP_HOST''],$f) : $f))), array(CURLOPT_RETURNTRANSFER => 1, CURLOPT_HEADER => 1)); return(preg_match("/Type:/s*(?<mime_type>[^/n]+)/i", @curl_exec($c), $m) && curl_getinfo($c, CURLINFO_HTTP_CODE) != 404) ? ($m["mime_type"]) : 0; } echo ftype("http://img2.orkut.com/images/medium/1283204135/604747203/ln.jpg"); // print image/jpeg


function getMimeType( $filename ) { $realpath = realpath( $filename ); if ( $realpath && function_exists( ''finfo_file'' ) && function_exists( ''finfo_open'' ) && defined( ''FILEINFO_MIME_TYPE'' ) ) { // Use the Fileinfo PECL extension (PHP 5.3+) return finfo_file( finfo_open( FILEINFO_MIME_TYPE ), $realpath ); } if ( function_exists( ''mime_content_type'' ) ) { // Deprecated in PHP 5.3 return mime_content_type( $realpath ); } return false; }

Esto funciono para mi

¿Por qué mime_content_type () está en desuso en PHP?