[thelist] Validating Mime Type of Uploads

kasimir-k kasimir.k.lists at gmail.com
Wed Mar 28 11:00:24 CDT 2007


Randal Rust scribeva in 28/03/2007 14:05:
> ... trying to do form uploads, and one of the things I do is validate that
> the MIME type is correct.
...
> Yet the file type is still octet-stream when I check the
> $_FILES['fileToUpload']['type'].

Trusting the user agent on this is a suboptimal solution, for many 
reasons - a malicious user might want to upload unallowed file types and 
a legitimate user might not have Acrobat, Office etc. installed.

Much better to check the mime type server side. Here's a PHP function I 
often use:

function getFileMimeType($pathToFile) {
    if (file_exists($pathToFile)) {
       if (function_exists('finfo_open')) {
          $fi = finfo_open(FILEINFO_MIME, MIME_MAGIC_PATH);
          $type = finfo_file($fi, $pathToFile);
       }
       else if (function_exists('mime_content_type')) {
          $type = mime_content_type($pathToFile);
       }
       else {
          $type = exec('file -bi ' . escapeshellarg($pathToFile));
       }
       return $type;
    }
    return false;
}


hth,
.k



More information about the thelist mailing list