PHP file upload check finfo_file

狂风中的少年 提交于 2019-12-24 12:23:05

问题


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

回答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



来源:https://stackoverflow.com/questions/33349716/php-file-upload-check-finfo-file

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!