Yii 1.1.16 and CUploadedFile


(Jpjounier) #1

Hi,

I have a webapp that stores files inside DB, in blob fields.

Since I have installed Yii 1.1.16, when I call an action that updates another field and does save() upon the model, my field storing binary data is flushed !

Very surprising side effect !

Maybe a side effect of the correction of this bug :

Bug #1257: CFileValidator is no longer unsafe by default to prevent setting arbitrary values. Instead, when no file is uploaded attribute is set to null (marcovtwout)

This is what my action does :




$file = Files::model()->findByAttributes(array('id' => $id, 'deleted' => '0'));

        if ($file !== null) {

            $file->nbdownloads++;

            $file->save();

        }




(Saurabhdhariwal737) #2

For this problem you have to check whether blob field is empty or not as below:


public function actionUpdate($id) {

        $model = $this->loadModel($id);

        $oldBlob = $model->file;


        if(isset($_POST['FileUpload']))        {

                $model->attributes=$_POST['FileUpload'];


                $file = CUploadedFile::getInstance($this,'file');


                if (!empty($file)) {

                        if ($file->size > 0) {

                                $model->file=file_get_contents($file->tmp_name);

                        }

                }

                else {

                        $model->file = $oldBlob;        // old blob field data is remained same here

                }


                if($model->save())

                        $this->redirect(array('view','id'=>$model->id));

        }

        ...

}

Let me know if you face any further query/concern regarding this.

Thanks

Saurabh Dhariwal


(Jpjounier) #3

I’m not sure you understand my problem.

I just want to update the counter of downloads when a file is downloaded.

I don’t call update() but save() and I know there will never be any uploaded file in that case, $_POST will never have any uploaded file.

I don’t understand why when I call save() after changing one integer field, my blob field is set to null.


(Phtamas) #4

Very likely.

Try to save the model without validation:


$file->save(false);


(Bizley) #5

This method might help http://www.yiiframework.com/doc/api/1.1/CActiveRecord#updateCounters-detail


(Jpjounier) #6

It works with save(false), thanks.

Anyway I find this behavior very weird.

For me, upgrading Yii should not have broken my code such a way, it shows there’s no backward compatibility.

Fortunately, I noticed the problem quickly, if not it would have been a serious problem ; each download was deleting the corresponding file content !

I think it’s the job of the developer to validate input data and set defaults values, the framework should not set cuploadedfile to null if there’s no uploaded file.

In my case, I can bypass validation rules but what if I needed them ?