Image Upload With Dimension Validation In Yii Model

This tutorial will help you to upload the image with image extension validation, image size validation and image dimension validation. So we can fix the width and height for image.

CFileValidator is used to validate the file or image types, image maximum size, image minimum size etc. To validate the dimension, we dont have option in CFileValidator. So I wrote a custom function ‘dimensionValidation()’ to check the image width and height, see the code below.

Model Validation

	public function rules()
	{
		............
		array('photo', 'file',
			'types'=>'jpg, gif, png',
			'maxSize'=>1024 * 1024 * 50,	// 50 MB
			'minSize'=>1024 * 1024 * 20,	// 20 MB
			'allowEmpty'=>true),
		array('photo','dimensionValidation'),
		.............
	}
	public function dimensionValidation($attribute,$param){
		if(is_object($this->photo)){
			list($width, $height) = getimagesize($this->photo->tempname);
			if($width!=150 || $height!=150)
				$this->addError('photo','Photo size should be 150*150 dimension');
		}	
	}

File Field In Yii Form

<?php
	.............
	<?php $form=$this->beginWidget('CActiveForm', array(
	.............
	'htmlOptions'=>array('enctype'=>'multipart/form-data')
	)); 
	?>
	.............
	<div class="row">
		<?php echo $form->labelEx($model,'photo'); ?>
        <?php echo CHtml::activeFileField($model, 'photo'); ?>
        <?php echo $form->error($model,'photo'); ?>	
	</div>

	............
?>

Single Image Upload Process In Controller

	public function actionCreate()
	{
		$model=new User;
		if(isset($_POST['User']))
		{
			$model->attributes=$_POST['User'];
			/** PHOTO **/
			$uploadedFile=CUploadedFile::getInstance($model,'photo');

			if($uploadedFile){
				$model->photo = $uploadedFile;
			}else{
				$model->photo=$model->oldphoto;
			}
			/** PHOTO **/	
			if($model->save()){
				$filepath=Yii::app()->basePath.'/../photos/';
				$ext = pathinfo($model->photo->name, PATHINFO_EXTENSION);
				$fileName = rand(0,9999).time().'.'.$ext; 		
				if($model->photo->saveAs($filepath.$fileName)){
					.............
				}
			}
		}
		.............
	}