(redirected from Main.FindingTheMimeTypeOfAFile)
On this page... (hide)
On *nix systems, the type of a file is called it's mimetype. Sometimes it is necessary to know the type of the file one is dealing with. You can't always rely on the file extension (there may not be one, or it may be incorrect). Thus, one has to check the type of the file by different means.
file() command
In *nix, there is a command called file() which returns a description of the file type. The options on file() vary on *nix platforms, but generally the following incantation will deliver just the file's mimetype:
will return the mimetype as it would be set in a Content-type: mail or http header. For example:
$ file -b --mime Main/Cartoons/aarp-eyechart.jpg image/jpeg
File::MimeInfo perl module
This can be used, but it does have some limitations. Instead, I use a Perl package called File::MimeInfo. It includes a program called mimetype with the proper parameters will return the mimetype of the file. With this information, you can do things like send an approrpriate Content-type header for an HTTP Response, or use it in setting Content-type for Mime mail or RSS enclosures.
Also important is to have a good database of MIME data. One such source is the Shared MIME data resource at Freedesktop.org: http://www.freedesktop.org/wiki/Software/shared-mime-info. On my main development machine, I have this database saved into /sw/share/mime, so I have aliased the mimetype program to: mimetype --database=/sw/share/mime.
Using mimetype in PHP
As of 5.3.0, PHP has the fileinfo class. This makes it easy to determine the true file type of a given file. Using the finfo_file function, it is easy to obtain the mime type:
- $finfo = new finfo(FILEINFO_MIME_TYPE);
- $mimetype = $finfo->file($filename);
For example:
$ php -r '$finfo = new finfo(FILEINFO_MIME_TYPE);print $finfo->file("Main/Cartoons/aarp-eyechart.jpg"). "\n";'
image/jpeg
Subsequently, doing something with that mimetype can become:
- $finfo = new finfo(FILEINFO_MIME_TYPE);
- switch ($finfo->file($filename)) {
- case 'image/jpeg': $ext = "jpg"; break;
- case 'image/gif': $ext = "gif"; break;
- case 'image/png': $ext = "png"; break;
- default: $ext = "dat"; break;
- }
Or, using a table:
- $mime2ext = array(
- 'image/jpeg' => 'jpg',
- 'image/jpg' => 'jpg',
- 'image/gif' => 'gif',
- 'image/png' => 'png',
- );
- // later, in code
- $ext = (isset($mime2ext[$finfo->file($filename)])) ? $mime2ext[$finfo->file($filename)] : 'dat';
| Tags: | Categories: Articles |
Recent Changes |
Printable View |
Page History |
Edit Page
Page last modified on April 09, 2012, at 10:41 AM by tamara