8

I’m working on an upload form in PHP that must allow only MP3 files.

When the upload is done, I analyze the file to check whether is it really an MP3. The first step is to detect the mime type as audio/mpeg. I use the libraries finfo_file() and works fine except that during the tests some MP3 files are rejected because their MIME type results as application/octet-stream.

My questions are:

  • Should my app definitely refuse those MP3 files? They actually play audio.
  • Is there any reason why this MIME type is an MP3?
  • is the detection of MIME type the most sure way to know the kind of file?
4

3 回答 3

3

在大多数需要上传的应用程序中,我有时会根据预定义的 MIME 类型列表验证浏览器(客户端)传递的 MIME。这种方法一般假设如果浏览器无法传达正在上传文件的 MIME 类型的可疑情况,我可能不想在此时处理它。

<?php

$valid_mp3_mimes = array(
    'audio/mpeg',
    'audio/x-mpeg',
    'audio/mp3',
    'audio/x-mp3',
    'audio/mpeg3',
    'audio/x-mpeg3',
    'audio/x-mpeg-3',
    'audio/mpg',
    'audio/x-mpg',
    'audio/x-mpegaudio',
    'video/mpeg',
    'video/x-mpeg',
);

$uploaded_file_mime = $_FILES['upload_field_name']['type'];

if(!in_array($uploaded_file_mime, $valid_mp3_mimes))
{
    die('Upload is not a valid MP3 file.');
}

您可能会或可能不会觉得这对您的目的来说已经足够了。PHP 手册明确指出,如果浏览器提供了此信息,则此信息可用,并且 MIME 类型未在服务器端检查,因此不应视为理所当然。

需要考虑的一件事是服务器上允许您验证文件的真正 MIME 类型的资源的可用性。

作为 PHP 开发人员,我们喜欢在大多数情况下创建独立于平台的代码的灵活性(例如,我们构建在运行 XAMPP 的 Windows 系统上的 Web 应用程序可以部署到 Linux 托管环境,只需很少的修改)。但是,在验证 MIME 类型时,我们开始引入需要验证这些工具是否存在的平台相关方法(例如“file”或“finfo_file”)。

这可能是一个值得研究的实现(取自 CodeIgniter GitHub 存储库),它利用了这些工具,并且与您将在 PHP 范围内获得的工作示例一样彻底:

如果可能,文件 MIME 类型会检测上载文件的(实际)MIME 类型。 https://github.com/EllisLab/CodeIgniter/blob/develop/system/libraries/Upload.php#L983


来源

PHP 手动 POST 方法上传 - http://www.php.net/manual/en/features.file-upload.post-method.php

网站管理员工具包 Mime 类型 - http://www.webmaster-toolkit.com/mime-types.shtml

FILExt .MP3 文件 - http://fileext.com/file-extension/MP3

于 2012-04-15T02:30:49.910 回答
0

除了 MIME 之外,最好的文件检测方法是使用“魔术字节”或“魔术数字”方案。Unix file(以及finfo_file)实际上使用“魔术字节”来执行此文件检测。所以,简而言之:是的。

不要太担心你的文件是什么样子,更多的是你可以用它做什么。只要它播放,文件应该没问题。

如果你真的想做更多,你可以自己检查魔术字节。这里有一个它们的列表

于 2012-04-08T05:08:56.590 回答
0

如果您想要一种非常健壮的方法来检测文件类型,而不仅仅是信任客户端提供正确的 MIME 类型,请使用UNIX 上的文件实用程序。

$ file Black\ Sands\ 01\ Prelude.mp3
Black Sands 01 Prelude.mp3: Audio file with ID3 version 2.2.0, contains: MPEG ADTS, layer III, v1, 320 kbps, 44.1 kHz, Stereo

$ file homework/math475-hw8.docx
homework/math475-hw8.docx: Microsoft Word 2007+

在 PHP 中,您可以使用exec函数来调用它。

于 2012-04-08T04:49:30.463 回答