RSS 2.0 Feed
Posted on May 6th, 2009 at 08:01 PM by Corey Ballou

I wanted to share a very quick snippet of code I conjured up to demonstrate the use of Kohana’s validation library to verify the proper size of an uploaded image submitted from form input. The height and width class vars specify the height/width or max height/max width of the image in pixels depending on the boolean value of EXACT_SIZE. If EXACT_SIZE is false, we assume that both the height and width of the uploaded image must be less than or equal to the two constant sizes.

<?php
class Test_Model extends Model { 

	const HEIGHT = 100;
	const WIDTH = 100;
	const EXACT_SIZE = true; 

	public function __construct() { parent::__construct(); } 

	/**
	 * Test function demonstrating how to utilize a callback function to
	 * validate an image's height and width requirements.
	 *
	 * @access public
	 * @param Input $input contains form post data
	 * @param array $file alias for $_FILES global
	 * @return mixed
	 */
	public function testValidation(Input $input, $files = array()) {

		// merge the $_POST and $_FILES arrays for validation
		// we could have also used Validation::factory() here to chain
		// together any filters, rules, and callbacks
		$post = new Validation(array_merge($input->post(), $file));
		$post->add_rules('image1', 'upload::required', 'upload::valid', 'upload::type[gif,jpg]', 'upload::size[5M]');
		$post->add_callback('image1', array($this, 'validateImageDimensions')); 

		// if the form has successfully validated, handle as necessary
		// most likely with a database insert or moving the uploaded file
		// for our example we will save the uploaded image to the filesystem
		if ($post->validate()) {
			// we need the extension to save the file properly since we are
			// allowing both GIF and JPG images to be uploaded
			$extension = strrchr($post->image1['name'], '.', '/absolute/path/');
			$filepath = upload::save('image1', 'newfilename'.$extension, 0644);
			return $filepath;
		} else {
			// throw an exception with the message contained within language file /i18n/en_US/test.php
			// from the multi-dimensional array index ['testValidation']['invalid']
			throw new Kohana_Exception('test.testValidation.invalid');
		}

	} 

	/**
	 * Function which validates the width and height of an image.
	 */
	public function validateImageDimensions(Validation $post, $field) { 

		if (array_key_exists($field, $post->errors())) return; 

		// ensure the image was actually uploaded to the temp dir before checking
		if (isset($post->{$field}) && !empty($post->{$field}['tmp_name'])) {
			list($width, $height) = getimagesize($post->{$field}['tmp_name']);
			// use predefined constants to determine whether we should be
			// checking for exact width and height or not
			if (self::$EXACT_SIZE === true) {
				if ($width != self::$WIDTH && $height != self::$HEIGHT) {
					$post->add_error($field, 'invalid_dimensions');
					return false;
				}
			} else {
				if ($width > self::WIDTH || $height > self::HEIGHT) {
					$post->add_error($field, 'invalid_dimensions');
					return false;
				}
			}
		} 

		return true; 

	} 

}
?>

My add_rules statement is by no means required for this example but demonstrates built in Kohana image validation. I could have just as easily created a Validation Factory and chained the instantiation of the validation class along with it’s rules. One thing to note is the call to the callback function itself. Since the callback is contained within the current model, Test_Model, we must access it in the same manner you would with the php function call_user_func.

The function getimagesize will return an array of 7 variables by default. In our case we simply need the first two array indices to obtain the width and height respectively.

Related Posts

Leave a Reply

Allowable tags
a, abbr, b, blockquote, cite, code, em, i, strike, strong, pre lang, line

* comment moderation is enabled and may delay your comment. There is no need to resubmit your comment.