Finfo_file on uploaded file to determine mime-type

JimmyBanks picture JimmyBanks · Feb 27, 2012 · Viewed 30.6k times · Source

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.

Answer

Lawrence Cherone picture Lawrence Cherone · Feb 27, 2012

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);
}
?>