1

I have a working PHP MIME validation script to check files that are uploaded to a website. Issue is with the current solution, that one can easily rename dodgy.php to become harmless.pdf and it will pass the validation and upload... I think I need to use the finfo_file PHP 5 logic to check the file more precisely but not sure on how best to integrate this to my current solution... Any advice? Current coded solution is as below, which should allow upload of just .doc, .docx and .pdf files:

$allowedExts = array(
  "pdf", 
  "doc", 
  "docx"
); 

$allowedMimeTypes = array( 
  'application/msword',
  'application/pdf',
  'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
  'application/x-pdf',
  'application/vnd.pdf'
);

$extension = end(explode(".", $_FILES["fileinputFileName"]["name"]));

if ( ! ( in_array($extension, $allowedExts ) ) ) {
//throw error 
$hook->addError('fileinputFileName','Please ensure you select a PDF, DOC or DOCX file.');
return $hook->hasErrors();
}

if ( in_array( $_FILES["fileinputFileName"]["type"], $allowedMimeTypes ) ) 
{
// all OK - proceed     
return true; 
}
else
{
//throw error
$hook->addError('fileinputFileName','Please ensure you select a PDF, DOC or DOCX file.');
return $hook->hasErrors();
}

Failing code example:

$finfo = new finfo(FILEINFO_MIME_TYPE);
if (false === $ext = array_search(
    $finfo->file($_FILES["fileinputFileName"]["tmp_name"]),
    array(
        'doc' => 'application/msword',
        'pdf' => 'application/pdf',
        'docx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
        'pdf' => 'application/x-pdf',
        'pdf' => 'application/vnd.pdf'
    ),
    // all OK - proceed     
    return true; 
)) {
    //die('Please provide another file type [E/3].');
    $hook->addError('fileinputFileName','Please ensure you select a PDF, DOC or DOCX file.');
    return $hook->hasErrors();
}
dubbs
  • 1,167
  • 2
  • 13
  • 34

1 Answers1

1

As you mention, relying on the file extension may not be the best strategy here. Instead, you may want to try to detect the mimetype of the file using finfo. From the PHP documentation:

// DO NOT TRUST $_FILES['upfile']['mime'] VALUE !!
// Check MIME Type by yourself.
$finfo = new finfo(FILEINFO_MIME_TYPE);
if (false === $ext = array_search(
    $finfo->file($_FILES['upfile']['tmp_name']),
    array(
        'jpg' => 'image/jpeg',
        'png' => 'image/png',
        'gif' => 'image/gif',
    ),
    true
)) {
    throw new RuntimeException('Invalid file format.');
}

http://php.net/manual/en/features.file-upload.php

Paul Bain
  • 4,364
  • 1
  • 16
  • 30