我有一个有效的PHP MIME验证脚本来检查上传到网站的文件。问题是当前的解决方案,人们可以轻松地将dodgy.php重命名为harmless.pdf并且它将通过验证并上传...我想我需要使用finfo_file PHP 5逻辑来更精确地检查文件但不是确定如何最好地将其与我当前的解决方案相结合......任何建议?当前编码的解决方案如下所示,它应该允许上传.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();
}
答案 0 :(得分:0)
正如您所提到的,依赖文件扩展名可能不是最佳策略。相反,您可能希望尝试使用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.');
}