Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finfo_file on uploaded file to determine mime-type

Im trying to determine the mime-type of an uploaded file, i want to use fileinfo(), this is what ive been trying, it isnt working:

$uploadedfile = $_FILES['soup']['tmp_name'];
if(isset($uploadedfile))
{
    $uploadedname = $_FILES['soup']['name'];
    $file=$uploadedsong;
    $file.=$uploadedname;
    $finfo = finfo_open(FILEINFO_MIME_TYPE); 
    $mime = finfo_file($finfo, $file);

Unfortunately the finfo_file doesnt seem to be running, Im assuming i have the following $file set incorrectly for this, is there a way i can do this properly with a newly uploaded file using $_FILE like this? or am i going at this problem the completely improper way. Using a file i have pre-set in another directly, and setting $file="folder/file.doc" works properly.

like image 747
JimmyBanks Avatar asked Feb 26 '12 23:02

JimmyBanks


People also ask

How is mime type determined?

MIME types are defined by three attributes: language (lang), encoding (enc), and content-type (type). At least one of these attributes must be present for each type. The most commonly used attribute is type. The server frequently considers the type when deciding how to generate the response to the client.

What is Finfo?

finfo::fileThis function is used to get information about a file.


2 Answers

You should be passing the path to the finfo_file function not the filename.

<?php 
if (isset($_FILES['soup']['tmp_name'])) {
    $finfo = finfo_open(FILEINFO_MIME_TYPE);
    $mime = finfo_file($finfo, $_FILES['soup']['tmp_name']);
    if ($mime == 'application/msword') {
        //Its a doc format do something
    }
    finfo_close($finfo);
}
?>
like image 147
Lawrence Cherone Avatar answered Oct 25 '22 20:10

Lawrence Cherone


I use the finfo() buffer() function as well as file_get_contents() from the php platform as below

$finfo = new finfo(FILEINFO_MIME);
$mimetype = $finfo->buffer(file_get_contents($filename)); #gives you mime type

you need to be on php 5.3 or higher and make sure you have the finfo() extension installed. for linux extension=fileinfo. and in windows: php_fileinfo.dll

you can have an array of accepted mime types and then check if it exists in that array

$acceptedMime = [];
if(in_array($mimetype, $acceptedMime, true) === true){
  #mime type is valid. Proceed!
}

Another alternative to avoid having to check mime types would be to store file uploads completely out of the document root folder.

like image 41
Rotimi Avatar answered Oct 25 '22 19:10

Rotimi