是否每个文件都有与之关联的 MIME 类型?

Does every file have a MIME type associated with it?

我最近实施了一个安全系统,我们根据可接受的列表检查 MIME 类型和文件扩展名。如果扫描文件在此列表中有 MIME 和扩展名,我们将继续。我在下面包含了我们扫描文件的功能。 ALLOWED_EXTENSIONSALLOWED_MIME_TYPES 只是字符串,例如 "txt,pdf,jpeg....".

我假设您知道 MIME 类型的工作原理和工作原理,但最近我们上传的 PDF 根本没有 MIME 类型。顺便说一句,这段代码大部分时间都有效。我已经看到 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;
}

经过几天的研究和建议,问题的答案有点无关紧要,因为首先检查 MIME 类型作为安全功能是不可行的。不同操作系统上的 MIME 类型存在太多问题,不同应用程序以不同方式保存文件,有些文件根本没有 MIME,最后,扩展名和 MIME 可能会被恶意用户或程序更改。关闭。

撇开 OP 自己的答案(不试图回答实际问题),这并不是很明确。内容类型 application/octet-stream 是通用的,因此可以分配给每个文件。另一方面,显然可以创建没有 useful 内容类型的文件;您如何根据 MIME 类型标记 dd if=/dev/urandom 的输出?

在这里的问题框架中,我倾向于 "no" -- 不可能为每个可能的文件分配一个有用的 MIME 类型。