Just thought I'd share this with whoever might find it useful...
Disclaimer: The code has not been thoroughly tested and I'm sure there is much room for improvement.
Suggestions and questions are welcome.
PHP Code:
<?php
require_once 'Zend/Validate/Abstract.php';
/**
* Validates an HTTP upload
*/
class Validate_Http_Upload extends Zend_Validate_Abstract
{
/**
* Validation failure message key for when the file's size is higher than the maximum size specified
*/
const MAX_SIZE_EXCEEDED = 'maxSizeExceeded';
/**
* Validation failure message key for when the file's mime type is not an allowed mime type
*/
const INVALID_MIME_TYPE = 'invalidMimeType';
/**
* Validation failure message template definitions
*
* @var array
*/
protected $_messageTemplates = array(
self::MAX_SIZE_EXCEEDED => "Max file size of '%max_file_size%' mb exceeded",
self::INVALID_MIME_TYPE => "Mime type '%invalid_mime_type%' is not allowed"
);
/**
* Additional variables available for validation failure messages
*
* @var array
*/
protected $_messageVariables = array(
'max_file_size' => '_max_file_size',
'invalid_mime_type' => '_invalid_mime_type'
);
/**
* Key found within the global $_FILES array
*
* @var string
*/
protected $_field;
/**
* Allowed mime types, e.g. application/pdf
*
* @var array
*/
protected $_allowed_mime_types;
/**
* Invalid mime type. For use in self::MAX_SIZE_EXCEEDED message
*
* @var string
*/
protected $_invalid_mime_type;
/**
* Maximum file size allowed.
*
* @var integer
*/
protected $_max_file_size;
/**
* Constructor
*
* @param string $field The name of the file field found within the $_FILES global array
* @param array $allowed_mime_types e.g., application/pdf or application/excel
* @param integer $max_file_size Size in bytes. Compared against $_FILES[$field]['size']
* @throws Zend_Validate_Exception
*/
public function __construct($field, $allowed_mime_types, $max_file_size)
{
/* Make sure the field actually exists */
if(isset($_FILES) && !empty($_FILES) && !array_key_exists($field, $_FILES)) {
require_once 'Zend/Validate/Exception.php';
throw new Zend_Validate_Exception($field . ' not found in global $_FILES array!');
}
$this->_field = $field;
$this->_allowed_mime_types = (array)$allowed_mime_types;
$this->_max_file_size = (int)$max_file_size;
}
public function isValid($value)
{
$this->_setValue($value);
/* Validate MIME type */
if(!in_array($_FILES[$this->_field]['type'], $this->_allowed_mime_types)) {
$this->_invalid_mime_type = $_FILES[$this->_field]['type'];
$this->_error(self::INVALID_MIME_TYPE);
return false;
}
/* Valiate size */
if($this->_max_file_size <= $_FILES[$this->_field]['size']) {
$this->_max_file_size = $this->_max_file_size/1024; // Convert to MB
$this->_error(self::MAX_SIZE_EXCEEDED);
return false;
}
return true;
}
}