我最近实施了一个安全系统,我们会检查MIME类型和文件扩展名是否在可接受的列表中。如果扫描的文件具有此列表中的MIME和扩展名,则我们继续进行。下面是我们扫描文件的函数。 ALLOWED_EXTENSIONS
和ALLOWED_MIME_TYPES
只是字符串,例如“ txt,pdf,jpeg ...”。
我假设您知道MIME类型是什么以及它们如何工作,但最近我们收到了没有任何MIME类型的PDF上传。顺便说一句,这段代码大多数时候都有效。我见过PDF、图像、文本文件等都可以通过。
一个文件完全没有MIME类型是可能的吗?
/**
* scan the file before upload to do our various security checks
*
* @param tmpName the file's location in /tmp, used for MIME type scan
* @param name the filename as it was uploaded, used for extension scan
* @param oid the order id, passed along to notifyStaffIllegalFileUpload() if email needs to be sent
* @return true on success, error string on failure
*/
function scanFile($tmpName, $name, $oid) {
global $_email;
// get lists from config
$allowedExtensions = explode(",", ALLOWED_EXTENSIONS);
$allowedMIMEs = explode(",", ALLOWED_MIME_TYPES);
// get extension
$ext = pathinfo($name, PATHINFO_EXTENSION);
// get MIME type
$finfo = finfo_open(FILEINFO_MIME_TYPE);
$mime = finfo_file($finfo, $tmpName);
finfo_close($finfo);
// check against allowed
if (!in_array(strtolower($ext), $allowedExtensions) || !in_array(strtolower($mime), $allowedMIMEs)) {
capDebug(__FILE__, __LINE__, "Order #" . $oid . " - A user attempted to upload a file with extension '" . $ext . "' and MIME type '" . $mime . "'. The attempt was blocked.\n", "/tmp/file_errors.log");
$_email->notifyStaffIllegalFileUpload($oid, $name, $ext, $mime);
return "Our security systems detected an illegal file type/mime type. The file upload was cancelled.";
}
return true;
}