PHP
downloads | documentation | faq | getting help | mailing lists | reporting bugs | php.net sites | links | conferences | my php.net

search for in the

xattr> <Fonctions Mimetype
Last updated: Fri, 05 Sep 2008

view this page in

mime_content_type

(PHP 4 >= 4.3.0, PHP 5)

mime_content_typeDétecte le type MIME d'un fichier (obsolète)

Description

string mime_content_type ( string $filename )

Retourne le type MIME du fichier filename en se basant sur les informations présentes dans le fichier magic.mime.

Liste de paramètres

filename

Chemin vers le fichier testé.

Valeurs de retour

Retourn le type de contenu MIME, comme text/plain ou encore application/octet-stream.

Notes

Avertissement

Cette fonction est devenue obsolète car l'extension PECL Fileinfo fournit la même fonctionnalité (et bien plus) d'une façon plus propre.

Exemples

Exemple #1 Exemple avec mime_content_type()

<?php
echo mime_content_type('php.gif') . "\n";
echo 
mime_content_type('test.php');
?>

L'exemple ci-dessus va afficher :

image/gif
text/plain

Voir aussi



xattr> <Fonctions Mimetype
Last updated: Fri, 05 Sep 2008
 
add a note add a note User Contributed Notes
mime_content_type
php [spat] hm2k.org
21-Aug-2008 10:52
I also had issues with this function.

The issue was that it would almost always return "text/plain".

echo ini_get('mime_magic.magicfile'); // returns /etc/httpd/conf/magic

I found that I needed the OS' magic.mime file instead.

You can either copy it to the existing location, or update your php.ini, you cannot use ini_set().

[root@blade conf]# mv magic magic.old
[root@blade conf]# cp /usr/share/magic.mime magic
[root@blade conf]# apachectl graceful

Note: you will see that I have gracefully restarted apache to ensure it has taken affect.
lukas v
10-Jul-2008 05:57
I cleaned up and compiled together code from different people here below. This code returns "unknown/<filesuffix>" if it can't something better.

<?php
   
function returnMIMEType($filename)
    {
       
preg_match("|\.([a-z0-9]{2,4})$|i", $filename, $fileSuffix);

        switch(
strtolower($fileSuffix[1]))
        {
            case
"js" :
                return
"application/x-javascript";

            case
"json" :
                return
"application/json";

            case
"jpg" :
            case
"jpeg" :
            case
"jpe" :
                return
"image/jpg";

            case
"png" :
            case
"gif" :
            case
"bmp" :
            case
"tiff" :
                return
"image/".strtolower($fileSuffix[1]);

            case
"css" :
                return
"text/css";

            case
"xml" :
                return
"application/xml";

            case
"doc" :
            case
"docx" :
                return
"application/msword";

            case
"xls" :
            case
"xlt" :
            case
"xlm" :
            case
"xld" :
            case
"xla" :
            case
"xlc" :
            case
"xlw" :
            case
"xll" :
                return
"application/vnd.ms-excel";

            case
"ppt" :
            case
"pps" :
                return
"application/vnd.ms-powerpoint";

            case
"rtf" :
                return
"application/rtf";

            case
"pdf" :
                return
"application/pdf";

            case
"html" :
            case
"htm" :
            case
"php" :
                return
"text/html";

            case
"txt" :
                return
"text/plain";

            case
"mpeg" :
            case
"mpg" :
            case
"mpe" :
                return
"video/mpeg";

            case
"mp3" :
                return
"audio/mpeg3";

            case
"wav" :
                return
"audio/wav";

            case
"aiff" :
            case
"aif" :
                return
"audio/aiff";

            case
"avi" :
                return
"video/msvideo";

            case
"wmv" :
                return
"video/x-ms-wmv";

            case
"mov" :
                return
"video/quicktime";

            case
"zip" :
                return
"application/zip";

            case
"tar" :
                return
"application/x-tar";

            case
"swf" :
                return
"application/x-shockwave-flash";

            default :
            if(
function_exists("mime_content_type"))
            {
               
$fileSuffix = mime_content_type($filename);
            }

            return
"unknown/" . trim($fileSuffix[0], ".");
        }
    }
?>
MKoper
01-Jul-2008 01:29
Regarding serkanyersen's example, i extended the extensions list

case "js":
                return "application/x-javascript";
            case "json":
                return "application/json";
            case "jpg":
            case "jpeg":
            case "jpe":
                return "image/jpg";
            case "png":
            case "gif":
            case "bmp":
            case "tiff":
                return "image/".strtolower($matches[1]);
            case "css":
                return "text/css";
            case "xml":
                return "application/xml";
            case "doc":
            case "docx":
                return "application/msword";
            case "xls":
            case "xlt":
            case "xlm":
            case "xld":
            case "xla":
            case "xlc":
            case "xlw":
            case "xll":
                return "application/vnd.ms-excel";
            case "ppt":
            case "pps":
                return "application/vnd.ms-powerpoint";
            case "rtf":
                return "application/rtf";
            case "pdf":
                return "application/pdf";
            case "html":
            case "htm":
            case "php":
                return "text/html";
            case "txt":
                return "text/plain";
            case "mpeg":
            case "mpg":
            case "mpe"
                return "video/mpeg";
            case "mp3":
                return "audio/mpeg3";
            case "wav":
                return "audio/wav";
            case "aiff":
            case "aif":
                return "audio/aiff";
            case "avi":
                return "video/msvideo";
            case "wmv":
                return "video/x-ms-wmv";
            case "mov":
                return "video/quicktime";
            case "zip":
                return "application/zip";
            case "tar":
                return "application/x-tar";
            case "swf":
                return "application/x-shockwave-flash";
memi aet liip doet ch
06-Jun-2008 02:59
Regarding serkanyersen's example : It is advisable to change the regular expression to something more precise like

preg_match("|\.([a-z0-9]{2,4})$|i", $filename, $m);

This makes sure that only the last few characters are taken. The original expression would not work if the filename is a relative path.
serkanyersen
29-Apr-2008 08:22
I've written an alternative for this. Not necessarily tested but it works OK on my server.

I hope this helps

<?
/**
 * Tries to get mime data of the file.
 * @return {String} mime-type of the given file
 * @param $filename String
 */
function get_mime($filename){
    preg_match("/\.(.*?)$/", $filename, $m);    # Get File extension for a better match
    switch(strtolower($m[1])){
        case "js": return "application/javascript";
        case "json": return "application/json";
        case "jpg": case "jpeg": case "jpe": return "image/jpg";
        case "png": case "gif": case "bmp": return "image/".strtolower($m[1]);
        case "css": return "text/css";
        case "xml": return "application/xml";
        case "html": case "htm": case "php": return "text/html";
        default:
            if(function_exists("mime_content_type")){ # if mime_content_type exists use it.
               $m = mime_content_type($filename);
            }else if(function_exists("")){    # if Pecl installed use it
               $finfo = finfo_open(FILEINFO_MIME);
               $m = finfo_file($finfo, $filename);
               finfo_close($finfo);
            }else{    # if nothing left try shell
               if(strstr($_SERVER[HTTP_USER_AGENT], "Windows")){ # Nothing to do on windows
                   return ""; # Blank mime display most files correctly especially images.
               }
               if(strstr($_SERVER[HTTP_USER_AGENT], "Macintosh")){ # Correct output on macs
                   $m = trim(exec('file -b --mime '.escapeshellarg($filename)));
               }else{    # Regular unix systems
                   $m = trim(exec('file -bi '.escapeshellarg($filename)));
               }
            }
            $m = split(";", $m);
            return trim($m[0]);
    }
}
?>
mami at madagascarsurlenet dot com
13-Nov-2007 10:58
Since I enabled the mime_magic extension on my IIS, I also got the error message "invalid magic file, disabled" in my phpinfo. After I add these lines to my php.ini, the message disappeared and it works great!

mime_magic.debug = Off
mime_magic.magicfile ="D:\PHP5\extras\magic.mime"

mime_magic.debug is by default off but without this line it fails. I'm using PHP 5.2.5.
Sune Jensen
29-Aug-2007 09:16
For me mime_content_type didn't work in Linux before I added

mime_magic.magicfile = "/usr/share/magic.mime"

to php.ini (remember to find the correct path to mime.magic)
dt at php dot net
14-Jun-2007 08:18
<?php
if (!function_exists('mime_content_type ')) {
    function
mime_content_type($filename) {
       
$finfo    = finfo_open(FILEINFO_MIME);
       
$mimetype = finfo_file($finfo, $filename);
       
finfo_close($finfo);
        return
$mimetype;
    }
}
?>
Quis at IHAVEGOTSPAMENOUGH dot omicidio dot nl
12-Feb-2007 09:28
<?PHP
 
function qmimetype($file) {
   
$ext=array_pop(explode('.',$file));
    foreach(
file('/usr/local/etc/apache22/mime.types') as $line)
      if(
preg_match('/^([^#]\S+)\s+.*'.$ext.'.*$/',$line,$m))
        return
$m[1];
    return
'application/octet-stream';
  }
?>

Not perfect, but works good enough for me ;)
tree2054 using hotmail
03-Nov-2006 05:59
The correct little correction:

exec will return the mime with a newline at the end, the trim() should be called with the result of exec, not the other way around.

<?php

if ( ! function_exists ( 'mime_content_type ' ) )
{
   function
mime_content_type ( $f )
   {
       return
trim ( exec ('file -bi ' . escapeshellarg ( $f ) ) ) ;
   }
}

?>
15-Oct-2006 07:06
if you use a transparent 'spacer' GIF i've found it needs to be a around 25x25 for it to register as 'image/gif'. otherwise it's read in as 'text/plain'.
webmaster at cafe-clope dot net
23-Feb-2006 05:31
Completing <some dude AT somewhere DOT com> comment:

0 string < ? php application/x-httpd-php

and string detection on text files may fail if you check a file encoded with signed UTF-8. The UTF-8 signature is a two bytes code (0xFF 0xFE) that prepends the file in order to force UTF-8 recognition (you may check it on an hexadecimal editor).
Y0Gi
25-Jan-2006 11:13
The 'file' utility fortunately is available for Windows, too:
http://gnuwin32.sourceforge.net/packages/file.htm
some dude AT somewhere DOT com
07-Oct-2005 09:44
I added these two lines to my magic.mime file:

0 string \<?php application/x-httpd-php
0 string
<?xml text/xml

The first one may not work
if "<?php" is not at the very beginning of your file, e.g., if some HTML preceeds the first bit of PHP code. The second one should work because "<?xml" *should* be the first thing in every XML file.
ginnsu at arcee dot ca
08-Mar-2005 10:14
The function mime_content_type only worked for me on Microsoft Windows after I added the directive "mime_magic.debug" to my php.ini with the value of "On". The default value appears to be "Off". Exampe:

[mime_magic]
mime_magic.debug = On
mime_magic.magicfile = "c:\php\extras\magic.mime"

xattr> <Fonctions Mimetype
Last updated: Fri, 05 Sep 2008
 
 
show source | credits | stats | sitemap | contact | advertising | mirror sites