【问题标题】:How to prevent malicious file upload?如何防止恶意文件上传?
【发布时间】:2016-12-19 08:14:25
【问题描述】:

我有上传文件的表单,但不幸的是它可以上传像php webshel​​l这样的恶意文件。

这是我的控制器代码。

public function actionIndex()
    {
        $model = new TbBank();
        $searchModel = new TbBankSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

        if ($model->load(Yii::$app->request->post())) {
            //get the instance of the uploaded file
            //return \yii\helpers\VarDumper::dump($model);
            $model->bank_code = Html::encode($model->bank_code);
            $model->nama = Html::encode($model->nama);
            $imageName = $model->bank_code;
            $model->file = UploadedFile::getInstance($model,'file');
            //save the path in the db column
            $path_image = \Yii::$app->params['uploadPath']."bank/";
            $model->logo =  $imageName.'.'.$model->file->extension;
            $model->save();
            if ($model->file->saveAs($path_image.$imageName.'.'.$model->file->extension)){
                return $this->redirect(['index', 'id' => $model->bank_id]);
            }else{
                \yii\helpers\VarDumper::dump($model);
            }
        } else {
            return $this->render('index', [
                'searchModel' => $searchModel,
                'dataProvider' => $dataProvider,
                'model' => $model,
            ]);
        }


    }

这是我的 TbBank 模型方法规则

public function rules()
    {
        return [
            [['bank_code', 'nama'], 'required'],
            [['bank_code'], 'string', 'max' => 10],
            [['nama'], 'string', 'max' => 50],        
            [['logo'], 'string', 'max' => 200],  
            [['file'],'file','skipOnEmpty'=>true,'extensions'=>'gif,jpg,jpeg,png','maxSize'=>100*1024*1],
            [['file'],'required','on'=>'create'],
        ];
    }

我需要的是当用户提交时,它会检查上传的文件是否包含恶意文件,如果文件安全则返回错误,然后将文件保存到存储中,然后记录保存。

经过一些谷歌搜索后,yii2 似乎没有内置功能来检查恶意文件。

提前致谢。

【问题讨论】:

    标签: yii2


    【解决方案1】:

    如果您没有正确检查验证规则,您希望它们如何工作?

    public function actionIndex()
    {
        // ...
    
        if ($model->load(Yii::$app->request->post())) {
    
            // ...
    
            // first prepare UploadedFile instance
            $model->file = UploadedFile::getInstance($model,'file');
    
            // THEN run validation AND IF everything is OK move on
            if ($model->validate()) {
    
                // VERIFY if save() is successful
                if ($model->save()) {
    
                    // THEN try to save file
                    if ($model->file->saveAs($path_image.$imageName.'.'.$model->file->extension)){
                        // ...
                    }
                }
            }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2011-02-03
      • 1970-01-01
      • 1970-01-01
      • 2013-08-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-17
      • 2019-02-01
      • 2010-10-10
      相关资源
      最近更新 更多