views:

508

answers:

2

I'm trying to check the MIME type of an uploaded file in my PHP application. I upload the file, then do this, where $file is the path to my file:

$finfo = new finfo(FILEINFO_MIME);
$mimetype = $finfo->file($file);

In this situation, $mimetype is always an empty string. I've tested on several file types (.jpg, .doc, .txt, .pdf) and it's always empty. It's supposed to return something like "image/jpeg".

I was debugging and changed the first line so that the code snippet is now this:

$finfo = new finfo(FILEINFO_NONE);
$info = $finfo->file($file);

In this situation, when I uploaded a jpg, $info was this: JPEG image data, JFIF standard 1.02. So now I know it's getting to the file correctly, but passing in FILEINFO_MIME doesn't give me back the correct mime string.

This only happens on my staging server. On my local server, I get the correct mime type. Does anyone have any ideas why my staging server returns an empty string for mime type?

A: 

Try this:

<?php
$fi = new finfo(FILEINFO_MIME,'/usr/share/file/magic');
$mime_type = $fi->buffer(file_get_contents($file));
?>
Calvin
This gives me back an empty string, as well.
Pamela
+1  A: 

I'm wondering if the magic file is correctly placed on your server.

magic_file
Name of a magic database file, usually something like /path/to/magic.mime. If not specified, the MAGIC environment variable is used. If this variable is not set either, /usr/share/misc/magic is used by default. A .mime and/or .mgc suffix is added if needed.

Since you can specify your own file Via the last argument

$finfo = new finfo(FILEINFO_MIME, "/usr/share/misc/magic");
Ólafur Waage
Thanks for the suggestion, but I am still getting back an empty string with this.
Pamela
My MIME file is in /usr/share/file/magic, but same result there, too.
Pamela