有比彻底的mime类型检查更好的方法来验证上传的文件实际上是一个电子表格吗?


laravel excel, is there a better way than a thorough mime type check to verify an uploaded file is in fact a spreadsheet?

我有一个允许用户上传电子表格的工具,然后我用larvel - excel解析电子表格。我的问题是,我怎么能检查文件是一个有效的excel文件之前试图解析它?

我看了看phoffice/larvel - excel文档,找不到验证文件的方法。所以,我的下一个猜测是,如果我尝试Load()一个无效文件,它将爆炸并给我一个警告或错误。但是,它不会这样做,而是解析文件并尝试以某种方式将其转换为电子表格。例如,我给它提供一个pdf,它确实生成了一个集合,其中包含它在pdf文件中可以找到的任何非二进制垃圾。这是不可取的。

目前,我正在做一个mime类型检查来验证文件。

//valid mime types
$mimeTypes = [
    'application/csv', 'application/excel',
    'application/vnd.ms-excel', 'application/vnd.msexcel',
    'text/csv', 'text/anytext', 'text/plain', 'text/x-c', 
    'text/comma-separated-values',
    'inode/x-empty',
    'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
             ];
$file = request()->hasFile('file');
if ($file) {
    if (in_array(request()->file('file')->getClientMimeType(), $mimeTypes)) {
        //then parse the file
        Config::set('excel.import.heading', 'original');
        $data = Excel::load(request()->file('file')->path(), function ($reader) {
        })->get();
         //do some stuff with data...
    } else {
        //invalid file
    }
} else {
    //no file uploaded
}

这并不理想,因为似乎有各种各样可能的mime类型,所以我必须主动维护列表,并且某些csv文件具有明文mime类型,因此非csv-明文文件在这里可以通过审查。是否有任何标准的方法,由Laravel, Laravel- excel或phoffice提供,以验证文件?

这不是对文件的MIME检查!

您只检查用户提供的文件扩展名信息。

string | null getClientMimeType()

返回文件mime类型

客户端mime类型是从上传文件的请求中提取的,所以它不应该被视为安全值

对于受信任的mime类型,使用getMimeType()代替(它根据文件内容猜测mime类型)。

Symfony Component HttpFoundation File UploadedFile

如果你想在上传的文件中验证神奇的MIME字节,你可以依赖于你的操作系统的神奇MIME字节文件,就像在PHP中这样。

$finfo = finfo_open(FILEINFO_MIME_TYPE); // return mime type ala mimetype extension
// $mime will contain the correct mime type
$mime = finfo_file($finfo, $_FILES['your-form-upload-input-name-here']['tmp_name'];
finfo_close($finfo);

参见finfo_file

要使用当前依赖的Symfony组件来执行此操作,请调用getMimeType()方法。注意,不同之处在于,getClientMimeType()使用的是客户端提供的不可信的信息,而getMimeType()所做的事情与上面的finfo_file()所演示的相同。