如何防止恶意文件上传?

时间:2016-12-19 08:14:26

标签: yii2

我有文件上传的表单,但不幸的是它可以上传像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没有内置功能来检查恶意文件。

提前致谢。

1 个答案:

答案 0 :(得分: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)){
                    // ...
                }
            }
        }
    }
}