Image Validation -> How to get Image-Objekt into Validator

Hey,

I’m writing my custom ImageValidator class (extending CValidator).

The Filename is passed via the $attribute Parameter correctly.

However when calling functions such as


getimagesize()

I get the following error:


getimagesize(DS76HJ.jpg): failed to open stream: No such file or directory 

here is my controller:




// Start Controller Fkt..

     $model->avatar=CUploadedFile::getInstance($model,'avatar');  // get image object..

     

     if($model->validate()) // Validate image..

     {

           // Do stuff is ok..

     }




and here part of my ImageValidation class…




class ImageValidator extends CValidator

{

        // ..Atts

     

        protected function validateAttribute($object,$attribute)

        {

		// Init Stuff..

                $value=$object->$attribute;  // Objekt is of class user!!


		if (getimagesize($value))   // put Image?? in getimagesize

		{

			// OK

		}

		else

		{

			// Error

                      $message=$this->message!==null?$this->message:Yii::t('yii','{attribute} File Validation failed - Save your image in MS Paint and try again!.',

                                array('{true}'=>$this->trueValue, '{false}'=>$this->falseValue));

                        $this->addError($object,$attribute,$message);

		}

      }


}



It’s because you are calling getimagesize() on a CUploadedFile object. This means of course that it will not find file in the tmp dir.

Make sure you have an instance of CUploadedFile (very easy to work with).




if(!$file instanceof CUploadedFile)

{

    $file = CUploadedFile::getInstance($object, $attribute);

    if(null===$file)

        return $this->emptyAttribute($object, $attribute);

}



Then you can simply call


$file->getSize();

Matt

Ok THX

Now it works…

created a file instance within my validator and called getimagesize():




$file=CUploadedFile::getInstance($object,'avatar');

getimagesize($file);



Glad it’s working.

The attribute should already be of CUploadedFile type. Take a look at CFileValidator to get some ideas. Basically, it should look something like:




    protected function validateAttribute($object, $attribute)

    {

        $file = $object->$attribute;

        if (!$file instanceof CUploadedFile)

        {

            $file = CUploadedFile::getInstance($object, $attribute);

            if (null === $file)

                return $this->emptyAttribute($object, $attribute);

        }

        $this->validateFile($object, $attribute, $file);

    }


    protected function validateFile($object, $attribute, $file)

    {

        // Do validation here

    }



Matt