Ressources documentaires pour Mandriva Linux et les Logiciels Libres

PHP Toolbox : determining file mimetype

On the extranet I developed for my society, the users have the ability to upload files, but I do restrict the files types depending on the document’s nature. That’s why i need a way to determined the mimetype of the document in PHP. For this I’m using finfo, here the code as used for a document which have been just uploaded.

function check_document_form($vars)
{
   // check if file have been correctly uploaded 
   if($_FILES['document']['error'] != 0)
   {
        return FALSE;	
    }

   $fres = finfo_open(FILEINFO_MIME); /* ask to return mime type */

    // it seems that sometimes finfo_file returns mimetype;charset=xxx
    // like "application/pdf;charset=binary"

   // return the first element of the array by using reset
  $mimetype=reset(explode(';',finfo_file($fres,$_FILES['document']['tmp_name'])));
  
   // $GLOBALS['mimetype_document_tab'] is a global array containing the list of authorized mimetype
  if(!in_array($mimetype, $GLOBALS['mimetype_document_tab']))
  {
      return FALSE;
  }
  finfo_close($fres);
  return TRUE;
}

The issue with finfo_file() returning the mimetype and the charset instead of just the mimetype happen with PHP 5.2.9 under Mandriva Spring. I know at least that the charset was not return with 5.2.5 under Mandriva 2008 Spring. As the mimetype and the charset are separated by a semi-column, I’m using explode with ‘;’ as a delimiter to split the string in an array, and then use reset to return the first element of the array. This codeworks even when finfo_file() return just the mimetype.

]]

Aucun commentaire jusqu'à présent.

Laisser un commentaire

Votre adresse de messagerie ne sera pas publiée. Les champs obligatoires sont indiqués avec *

Catégories

My Tweets