PHP文件上传检查finfo_文件

PHP文件上传检查finfo_文件,php,upload,Php,Upload,我有一个工作的PHP MIME验证脚本来检查上传到网站的文件。问题在于当前的解决方案,可以很容易地将dodgy.php重命名为无害的.pdf,它将通过验证并上传。。。我想我需要使用Finfou文件PHP5逻辑来更精确地检查文件,但不确定如何最好地将其集成到我当前的解决方案中。。。有什么建议吗?当前编码的解决方案如下,只允许上载.doc、.docx和.pdf文件: $allowedExts = array( "pdf", "doc", "docx" ); $allowedMim

我有一个工作的PHP MIME验证脚本来检查上传到网站的文件。问题在于当前的解决方案,可以很容易地将dodgy.php重命名为无害的.pdf,它将通过验证并上传。。。我想我需要使用Finfou文件PHP5逻辑来更精确地检查文件,但不确定如何最好地将其集成到我当前的解决方案中。。。有什么建议吗?当前编码的解决方案如下,只允许上载.doc、.docx和.pdf文件:

$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();
}
失败代码示例:

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

正如您所提到的,依赖文件扩展名可能不是这里的最佳策略。相反,您可能希望尝试使用finfo检测文件的mimetype。从PHP文档中:

// 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.');
}

谢谢Paul-我以为我的代码在检查Mime类型?我相信这里发送的类型不是从文件推断出来的,而是基于文件名。好的。刚尝试过实现,但遇到了服务器错误。我正在使用的代码包含在上面更新的问题中。知道问题是什么吗?日志中没有显示任何异常的内容!它在mime类型脚本上出现了一个错误,但您使用的是什么版本的PHP?它在5.3.0及以上版本中。