Laravel 5安全上传文档文件


Laravel 5 safe upload document files

在这种情况下,我想安全上传pdf, doc, docx, ppt, pptx, xls, xlsx, rar, zip,防止任意文件上传,特别是web shell或任何邪恶的脚本。

问题是我如何验证文件,是安全的上传?防止绕过,如更改mime类型与篡改数据,重命名文件与多个扩展名,在文件名中使用;和空格,小写和大写的文件扩展名等。

我的控制器代码是这样的

public function fileUpload(){
    $ext = ['pdf', 'doc', 'ppt', 'xls', 'docx', 'pptx', 'xlsx', 'rar', 'zip'];
    $data = Request::all();
    $name = $data['file']->getClientOriginalName();
    $rules = [
        'file' => 'required'
    ];
    $v = Validator::make($data, $rules);
    if($v->passes()){
        // Check safe file validation
        // should here or something? and how to prevent bypass
        // arbitrary file upload especially evil script.
        $data['file']->move(public_path('assets/uploads'), $name);
        return 'file uploaded';
    }else{
        return 'file upload failed';
    }

}

我建议查看Laravel Middleware进行验证。这将减少控制器中的代码,并允许它们被重用。

我个人将任何上传的文件的名称更改为随机的。如果需要,我总是可以将原始文件名保存在系统的某个地方。

我还会考虑使用htaccess命令来阻止该文件夹中的文件执行。

以下控制器方法

注意:它使用App'Http'Requests'CreateUploadRequest;

public function store(CreateUploadRequest $request)
{
    $file = Input::file('file');
    $destinationPath = 'assets/uploads'; // upload path
    $name = $file->getClientOriginalName(); // getting original name
    $fileName = time().rand(11111, 99999) . '.' . $extension; // renaming image
    $extension = $file->getClientOriginalExtension(); // getting fileextension
    $file->save($destinationPath.'/'.$fileName); // uploading file to given path

}
中间件

<?php namespace App'Http'Requests;
use App'Http'Requests'Request;
class CreateUploadRequest extends Request {
    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'file' => 'required_if:update,false|mimes:pdf,doc,ppt,xls,docx,pptx,xlsx,rar,zip|max:1000'
        ];
    }
}

我想这个想法来自于一个广播视频。我去找找看能不能找到。