Playing with Zend (file validators)

i’m working on a web project, and the php-framework that the clients use is Zend Framework, on my opinion, Codeigniter is “Harder, Better, Faster, Stronger”, starting with the DB class, and meny other things.

But, this post is not to talk about the good and bad things of zend, this post is about how to create filevalidators in Zend.

When we are trying to upload file’s with a form (we can use Zend form class) this tools helpus to validate some facts about the files we are receiving.

First we need to declare an object

$fileUpload = new Zend_File_Transfer_Adapter_Http();

then we can declare the validators

Example:

//this create a file extension validator, only accepts jpg, gif and png images

$fileUpload->addValidator(‘Extension’,true,’jpg,gif,png’);

//this one, creates a file size validator from a range to 10 kb to 60kb

$fileUpload->addValidator(‘FilesSize’,false,array(‘min’ => 10240,’max’ => 61440));

//and this is for images size, we can set the min and max width and height

$fileUpload->addValidator(‘ImageSize’,false,array(‘minwidth’ => 235,
‘maxwidth’ => 235,
‘minheight’ => 412,
‘maxheight’ => 412));

Now, probably we are iterating with more than 1 file, and need special sizes, extensions for each one, in that case, we can do a switch statement and create validators inside of every case depending our needs

This instruction is very useful too:

$fileUpload->removeValidator(‘Extension’);

In this case we are reomiving the extension validator, beacause maybe sometimes in one case of the switch statement, we don’t need to check the extension of a file, we can do the same with the others validators:

$fileUpload->removeValidator(‘ImageSize’);   
$fileUpload->removeValidator(‘FilesSize’);