Validating an images dimensions through Model validation
Since Cake's default model validation really doesn't support files that well, we have to build the methods our self. Right now I will be showing you how to validate an images dimensions. The method will either check the width, the height or both width and height. Simply place the following code in your AppModel.
/**
* Checks an image dimensions
*
* @param array $data
* @param int $width
* @param int $height
* @return boolean
*/
public function dimension($data, $width = 100, $height = null) {
$data = array_values($data);
$field = $data[0];
if (empty($field['tmp_name'])) {
return false;
} else {
$file = getimagesize($field['tmp_name']);
if (!$file) {
return false;
}
$w = $file[0];
$h = $file[1];
$width = intval($width);
$height = intval($height);
if ($width > 0 && $height > 0) {
return ($w > $width || $h > $height) ? false : true;
} else if ($width > 0 && !$height) {
return ($w > $width) ? false : true;
} else if ($height > 0 && !$width) {
return ($h > $height) ? false : true;
} else {
return false;
}
}
return true;
}
To use this validation, you would write it like any other custom validation rule. Lets set up our example view and model validation.
// View
echo $form->create('TestModel', array('type' => 'file'));
echo $form->input('image', array('type' => 'file'));
echo $form->end('Upload');
// Model
class TestModel extends AppModel {
public $validate = array(
'image' => array(
'rule' => array('dimensions', 500, 500),
'message' => 'Your image dimensions are incorrect: 500x500'
)
);
}
Now all you have to do is validate the data using your Models save() or validates() method. If the image fails the dimensions, the error should appear next to the field.
Problems with allowEmpty on files
Since the file support in Cake is lacking, you cannot use allowEmpty equals true. So this means that your image validation fields will always be required. There is currently a Trac bug for this with a quick fix.