19.2. Validators for Zend_File_Transfer

Zend_File_Transfer is delivered with several file related validators which should be used to increase security and prevent possible attacks. Note that the validators are only as good as you are using them. All validators which are provided with Zend_File_Transfer can be found in the Zend_Validator component and are named Zend_Validate_File_*. The following validators are actually available:

19.2.1. Using validators with Zend_File_Transfer

The usage of validators is quite simple. There are several methods for adding and manipulating validators.

  • isValid($files = null): Checks the given files using all set validators. $files may be either a real filename, or the elements name or the name of the temporary file.

  • addValidator($validator, $breakChainOnFailure, $options = null, $files = null): Adds the given validator to the validator stack (optionally only to the file(s) specified). $validator may be either an actual validator instance, or a short name specifying the validator type (e.g., 'Count').

  • addValidators(array $validators, $files = null): Adds the given validators to the stack of validators. Each entry may be either a validator type/options pair, or an array with the key 'validator' specifying the validator (all other options will be considered validator options for instantiation).

  • setValidators(array $validators, $files = null): Overwrites any existing validators with the validators specified. The validators should follow the syntax for addValidators().

  • hasValidator($name): Indicates if a validator has been registered.

  • getValidator($name): Returns a previously registered validator.

  • getValidators($files = null): Returns registered validators; if $files is passed, returns validators for that particular file or set of files.

  • removeValidator($name): Removes a previously registered validator.

  • clearValidators(): Clears all registered validators.

Example 19.5. Add validators to a file transfer

$upload = new Zend_File_Transfer();

// Set a filesize with 20000 bytes
$upload->addValidator('Size', false, 20000);

// Set a filesize with 20 bytes minimum and 20000 bytes maximum
$upload->addValidator('Size', false, array('min' => 20, 'max' => 20000));

// Set a filesize with 20 bytes minimum and 20000 bytes maximum and
// a file count in one step
$upload->setValidators(array(
    'Size'  => array('min' => 20, 'max' => 20000),
    'Count' => array('min' => 1, 'max' => 3),
));

            

Example 19.6. Limit validators to single files

addValidator(), addValidators(), and setValidators() each accept a final $files argument. This argument can be used to specify a particular file or array of files on which to set the given validator.

$upload = new Zend_File_Transfer();

// Set a filesize with 20000 bytes and limits it only to 'file2'
$upload->addValidator('Size', false, 20000, 'file2');

            

Generally you should simply use the addValidators() method, which can be called multiple times.

Example 19.7. Add multiple validators

Often it's simpler just to call addValidator() multiple times. One call for each validator. This also increases the readability and makes your code more maintainable. As all methods provide a fluent interface you can couple the calls as shown below:

$upload = new Zend_File_Transfer();

// Set a filesize with 20000 bytes
$upload->addValidator('Size', false, 20000)
       ->addValidator('Count', false, 2)
       ->addValidator('Filessize', false, 25000);

            

[Note] Note

Note that even though setting the same validator multiple times is allowed, doing so can lead to issues when using different options for the same validator.

And last but not least you can simply check the files using isValid().

Example 19.8. Validate the files

isValid() accepts the up- or downloaded filename, the temporary filename and of course also the name of the form element. If no parameter or null is given all files will be validated

$upload = new Zend_File_Transfer();

// Set a filesize with 20000 bytes
$upload->addValidator('Size', false, 20000)
       ->addValidator('Count', false, 2)
       ->addValidator('Filessize', false, 25000);

if ($upload->isValid()) {
    print "Validation failure";
}

            

[Note] Note

Note that isValid() will be called automatically when you receive the files and have not called it before.

When validation has failed it is probably a good idea to get informations about the found problems. Therefor you can use the methods getMessages() which returns all validation messages as array, getErrors() which returns all error codes, and hasErrors() which returns true as soon as a validation error has been found.

19.2.2. Count validator

The Count validator checks for the number of files which are provided. It supports the following option keys:

  • min: Sets the minimum number of files to transfer.

    [Note] Note

    Beware: When using this option you must give the minimum number of files when calling this validator the first time; otherwise you will get an error in return.

    With this option you can define the minimum number of files you expect to receive.

  • max: Set the maximum number of files to transfer.

    With this option you can limit the number of files which are accepted but also detect a possible attack when more files are given than defined in your form.

You can initiate this validator with an string or integer, the value will be used as max. But you can also use the methods setMin() and setMax() to set both options afterwards and getMin() and getMax() to retrieve the actual set values.

Example 19.9. Using the Count validator

$upload = new Zend_File_Transfer();

// Limit the amount of files to maximum 2
$upload->addValidator('Count', false, 2);

// Limit the amount of files to maximum 5 and expects minimum 1 file
// to be returned
$upload->addValidator('Count', false, array('min' =>1, 'max' => 5));

            

[Note] Note

Note that this validator stores the number of checked files internally. The file which exceeds the maximum will be returned as error.

19.2.3. Crc32 validator

The Crc32 validator checks the content of a transferred file by hashing it. This validator uses the hash extension from php with the crc32 algorithm. It supports the following options:

  • *: You can set any key or use a numeric array. The values will be used as hash to validate against.

    You can set multiple hashes by using different keys. Everyone will be checked and only if all fails, the validation itself will fail.

Example 19.10. Using the Crc32 validator

$upload = new Zend_File_Transfer();

// Checks is the content of the uploaded file has the given hash
$upload->addValidator('Crc32', false, '3b3652f');

// Limits this validator to two different hashes
$upload->addValidator('Crc32', false, array('3b3652f', 'e612b69'));

            

19.2.4. ExcludeExtension validator

The ExcludeExtension validator checks the file extension of files which are provided. It supports the following options:

  • *: You can set any key or use a numeric array. The values will be used as extension to check if the given file does not use this file extension.

  • case: Sets if validation should be done case sensitive. Default is not case sensitive. Note the this key is used for all used extensions.

This validator accepts multiple extensions either as a comma-delimited string, or as an array. You may also use the methods setExtension(), addExtension(), and getExtension() to set and retrieve extensions.

In some cases it is useful to test case sensitive. Therefor the constructor allows a second parameter $case which, if set to true, will validate the extension case sensitive.

Example 19.11. Using the ExcludeExtension validator

$upload = new Zend_File_Transfer();

// Do not allow files with extension php or exe
$upload->addValidator('ExcludeExtension', false, 'php,exe');

// Do not allow files with extension php or exe but use array notation
$upload->addValidator('ExcludeExtension', false, array('php', 'exe'));

// Check case sensitive
$upload->addValidator('ExcludeExtension',
                      false,
                      array('php', 'exe', 'case' => true));

            

[Note] Note

Note that this validator just checks the file extension. It does not check the actual file MIME type.

19.2.5. ExcludeMimeType validator

The ExcludeMimeType validator checks for the mimetype of transferred files. It supports the following options:

  • *: You can set any key or use a numeric array. Set the mimetype type to validate against.

    With this option you can define the mimetype of files which will not be accepted.

This validator accepts multiple mimetype either as a comma-delimited string, or as an array. You may also use the methods setMimeType(), addMimeType(), and getMimeType() to set and retrieve mimetype.

Example 19.12. Using the ExcludeMimeType validator

$upload = new Zend_File_Transfer();

// Does not allow mimetype of gif images for all files
$upload->addValidator('ExcludeMimeType', false, 'image/gif');

// Does not allow mimetype of gif and jpg images for all given files
$upload->addValidator('ExcludeMimeType', false, array('image/gif',
                                                      'image/jpeg');

// Does not allow mimetype of the group images for all given files
$upload->addValidator('ExcludeMimeType', false, 'image');

            

The above example shows that it is also possible to limit disallow mimetypes to a group of mimetypes. To disallow all images just use 'image' as mimetype. This can be used for all groups of mimetypes like 'image', 'audio', 'video', 'text, and so on.

[Note] Note

Note that disallowing groups of mimetypes will disallow all members of this group even if this was not your intention. When you disallow 'image' you will disallow all types of image like 'image/jpeg' or 'image/vasa'. When you are not sure if you want to disallow all types you should better disallow only defined mimetypes instead of the complete group.

19.2.6. Exists validator

The Exists validator checks for the existence of files which are provided. It supports the following options:

  • *: You can set any key or use a numeric array. Checks if the file exists in the given directory.

This validator accepts multiple directories either as a comma-delimited string, or as an array. You may also use the methods setDirectory(), addDirectory(), and getDirectory() to set and retrieve directories.

Example 19.13. Using the Exists validator

$upload = new Zend_File_Transfer();

// Add the temp directory to check for
$upload->addValidator('Exists', false, '\temp');

// Add two directories using the array notation
$upload->addValidator('Exists',
                      false,
                      array('\home\images', '\home\uploads'));

            

[Note] Note

Note that this validator checks if the file exists in all set directories. The validation will fail if the file does not exist in any of the given directories.

19.2.7. Extension validator

The Extension validator checks the file extension of files which are provided. It supports the following options:

  • *: You can set any key or use a numeric array. Checks if the given file uses this file extension.

  • case: Sets if validation should be done case sensitive. Default is not case sensitive. Note the this key is used for all used extensions.

This validator accepts multiple extensions either as a comma-delimited string, or as an array. You may also use the methods setExtension(), addExtension(), and getExtension() to set and retrieve extensions.

In some cases it is useful to test case sensitive. Therefor the constructor allows a second parameter $case which, if set to true, will validate the extension case sensitive.

Example 19.14. Using the Extension validator

$upload = new Zend_File_Transfer();

// Limit the extensions to jpg and png files
$upload->addValidator('Extension', false, 'jpg,png');

// Limit the extensions to jpg and png files but use array notation
$upload->addValidator('Extension', false, array('jpg', 'png'));

// Check case sensitive
$upload->addValidator('Extension', false, array('mo', 'png', 'case' => true));
if (!$upload->isValid('C:\temp\myfile.MO')) {
    print 'Not valid due to MO instead of mo';
}

            

[Note] Note

Note that this validator just checks the file extension. It does not check the actual file MIME type.

19.2.8. FilesSize validator

The FilesSize validator checks for the aggregate size of all transferred files. It supports the following options:

  • min: Sets the minimum aggregate filesize.

    With this option you can define the minimum aggregate filesize of files you expect to transfer.

  • max: Sets the maximum aggregate filesize.

    With this option you can limit the aggregate filesize of all files which are transferred, but not the filesize of individual files.

  • bytestring: Defines if a failure is returned with a userfriendly number, or with the plain filesize.

    With this option you can define if the user gets '10864' or '10MB'. Default value is true which returns '10MB'.

You can initiate this validator with only a string which will then be used as max. But you can also use the methods setMin() and setMax() to set both options afterwards and getMin() and getMax() to receive the actual set values.

The size itself is also accepted in SI notation as done by most operating systems. Instead of 20000 bytes you can just give 20kB. All units are converted by using 1024 as base value. The following Units are accepted: kB, MB, GB, TB, PB and EB. As mentioned you have to note that 1kB is equal to 1024 bytes.

Example 19.15. Using the FilesSize validator

$upload = new Zend_File_Transfer();

// Limit the size of all given files to 40000 bytes
$upload->addValidator('FilesSize', false, 40000);

// Limit the size of all given files to maximum 4MB and mimimum 10kB
$upload->addValidator('FilesSize',
                      false,
                      array('min' => '10kB', 'max' => '4MB'));

// As before, but returns the plain filesize instead of a userfriendly string
$upload->addValidator('FilesSize',
                      false,
                      array('min' => '10kB',
                            'max' => '4MB',
                            'bytestring' => false));

            

[Note] Note

Note that this validator stores the filesize of checked files internally. The file which exceeds the size will be returned as error.

19.2.9. ImageSize validator

The ImageSize validator checks for the size of image files. It supports the following options:

  • minheight: Sets the minimum image height.

    With this option you can define the minimum height of the image you want to validate.

  • maxheight: Sets the maximum image height.

    With this option you can limit the maximum height of the image you want to validate.

  • minwidth: Sets the minimum image width.

    With this option you can define the minimum width of the image you want to validate.

  • maxwidth: Sets the maximum image width.

    With this option you can limit the maximum width of the image you want to validate.

You can also use the methods setImageMin() and setImageMax() to set both minimum and maximum values to set the options afterwards and getMin() and getMax() to receive the actual set values.

For your convenience there is also a setImageWidth and setImageHeight method which will set the minimum and maximum height and width. Of course also the related getImageWidth and getImageHeight methods are available.

To suppress the validation of a dimension just don't set the related option.

Example 19.16. Using the ImageSize validator

$upload = new Zend_File_Transfer();

// Limit the size of a image to a height of 100-200 and a width of
// 40-80 pixel
$upload->addValidator('ImageSize', false,
                      array('minwidth' => 40,
                            'maxwidth' => 80,
                            'minheight' => 100,
                            'maxheight' => 200)
                      );

// Set other image dimensions
$upload->setImageWidth(array('minwidth' => 20, 'maxwidth' => 200));

            

19.2.10. IsCompressed validator

The IsCompressed validator checks if a transferred file is a compression archive like zip or arc. This validator is based on the MimeType validator and supports the same methods and options. You can limit this validator to special compression types with the methods described there.

Example 19.17. Using the IsCompressed validator

$upload = new Zend_File_Transfer();

// Checks is the uploaded file is a compression archive
$upload->addValidator('IsCompressed', false);

// Limits this validator to zip files only
$upload->addValidator('IsCompressed', false, array('application/zip'));

// Limits this validator to zip files only but uses a simpler notation
$upload->addValidator('IsCompressed', false, 'zip');

            

[Note] Note

Note that there is no check if you set a file type which is not a compression type. So it would be possible to define gif files to be accepted by this validator even if this is not logically.

19.2.11. IsImage validator

The IsImage validator checks if a transferred file is a image file like gif or jpeg. This validator is based on the MimeType validator and supports the same methods and options. You can limit this validator to special image types with the methods described there.

Example 19.18. Using the IsImage validator

$upload = new Zend_File_Transfer();

// Checks is the uploaded file is a image file
$upload->addValidator('IsImage', false);

// Limits this validator to gif files only
$upload->addValidator('IsImage', false, array('application/gif'));

// Limits this validator to jpeg files only but uses a simpler notation
$upload->addValidator('IsImage', false, 'jpeg');

            

[Note] Note

Note that there is no check if you set a file type which is not a image type. So it would be possible to define zip files to be accepted by this validator even if this is not logically.

19.2.12. Hash validator

The Hash validator checks the content of a transferred file by hashing it. This validator uses the hash extension from php. It supports the following options:

  • *: You can set any key or use a numeric array. Sets the hash to validate against.

    You can set multiple hashes by giving them as array. Everyone will be checked and only if all fails, the validation itself will fail.

  • algorithm: Sets the algorithm to use for hashing the content.

    You can set multiple algorithm by using the addHash() method multiple times.

Example 19.19. Using the Hash validator

$upload = new Zend_File_Transfer();

// Checks is the content of the uploaded file has the given hash
$upload->addValidator('Hash', false, '3b3652f');

// Limits this validator to two different hashes
$upload->addValidator('Hash', false, array('3b3652f', 'e612b69'));

// Sets a different algorithm to check against
$upload->addValidator('Hash',
                      false,
                      array('315b3cd8273d44912a7',
                            'algorithm' => 'md5'));

            

[Note] Note

This validator supports about 34 different hash algorithms. The most known are 'crc32', 'md5' and 'sha1'. When you want to know the others see php's hash_algos method.

19.2.13. Md5 validator

The Md5 validator checks the content of a transferred file by hashing it. This validator uses the hash extension from php with the md5 algorithm. It supports the following options:

  • *: You can set any key or use a numeric array. Sets the hash to validate against.

    You can set multiple hashes by giving them as array. Everyone will be checked and only if all fails, the validation itself will fail.

Example 19.20. Using the Md5 validator

$upload = new Zend_File_Transfer();

// Checks is the content of the uploaded file has the given hash
$upload->addValidator('Md5', false, '3b3652f336522365223');

// Limits this validator to two different hashes
$upload->addValidator('Md5',
                      false,
                      array('3b3652f336522365223',
                            'eb3365f3365ddc65365'));

            

19.2.14. MimeType validator

The MimeType validator checks for the mimetype of transferred files. It supports the following options:

  • *: You can set any key or use a numeric array. Set the mimetype type to validate against.

    With this option you can define the mimetype of files which will be accepted.

  • magicfile: The magicfile which shall be used.

    With this option you can define magicfile to use. When it's not set or empty, the MAGIC constant will be used instead. This option is available since Zend Framework 1.7.1.

This validator accepts multiple mimetype either as a comma-delimited string, or as an array. You may also use the methods setMimeType(), addMimeType(), and getMimeType() to set and retrieve mimetype.

You can also set the magicfile which shall be used by fileinfo with the 'magicfile' option. Additionally there are convenient setMagicFile() and getMagicFile() methods which allow later setting and retrieving of the magicfile parameter. This methods are available since Zend Framework 1.7.1.

Example 19.21. Using the MimeType validator

$upload = new Zend_File_Transfer();

// Limit the mimetype of all given files to gif images
$upload->addValidator('MimeType', false, 'image/gif');

// Limit the mimetype of all given files to gif and jpeg images
$upload->addValidator('MimeType', false, array('image/gif', 'image/jpeg');

// Limit the mimetype of all given files to the group images
$upload->addValidator('MimeType', false, 'image');

// Use a different magicfile
$upload->addValidator('MimeType',
                      false,
                      array('image',
                            'magicfile' => '/path/to/magicfile.mgx'));

            

The above example shows that it is also possible to limit the accepted mimetype to a group of mimetypes. To allow all images just use 'image' as mimetype. This can be used for all groups of mimetypes like 'image', 'audio', 'video', 'text, and so on.

[Note] Note

Note that allowing groups of mimetypes will accept all members of this group even if your application does not support them. When you allow 'image' you will also get 'image/xpixmap' or 'image/vasa' which could be problematic. When you are not sure if your application supports all types you should better allow only defined mimetypes instead of the complete group.

[Note] Note

This component will use the fileinfo extension if it is available. If it's not, it will degrade to the mime_content_type function. And if the function call fails it will use the mimetype which is given by HTTP.

You should be aware of possible security problems when you have whether fileinfo nor mime_content_type available. The mimetype given by HTTP is not secure and can be easily manipulated.

19.2.15. NotExists validator

The NotExists validator checks for the existence of files which are provided. It supports the following options:

  • *: You can set any key or use a numeric array. Checks if the file does not exist in the given directory.

This validator accepts multiple directories either as a comma-delimited string, or as an array. You may also use the methods setDirectory(), addDirectory(), and getDirectory() to set and retrieve directories.

Example 19.22. Using the NotExists validator

$upload = new Zend_File_Transfer();

// Add the temp directory to check for
$upload->addValidator('NotExists', false, '\temp');

// Add two directories using the array notation
$upload->addValidator('NotExists', false,
                      array('\home\images',
                            '\home\uploads')
                     );

            

[Note] Note

Note that this validator checks if the file does not exist in all of the set directories. The validation will fail if the file does exist in any of the given directories.

19.2.16. Sha1 validator

The Sha1 validator checks the content of a transferred file by hashing it. This validator uses the hash extension from php with the md5 algorithm. It supports the following options:

  • *: You can set any key or use a numeric array. Sets the hash to validate against.

    You can set multiple hashes by giving them as array. Everyone will be checked and only if all fails, the validation itself will fail.

Example 19.23. Using the Sha1 validator

$upload = new Zend_File_Transfer();

// Checks is the content of the uploaded file has the given hash
$upload->addValidator('Sha1', false, '3b3652f336522365223');

// Limits this validator to two different hashes
$upload->addValidator('Sha1',
                      false, array('3b3652f336522365223',
                                   'eb3365f3365ddc65365'));

            

19.2.17. Size validator

The Size validator checks for the size of a single file. It supports the following options:

  • min: Set the minimum filesize.

    With this option you can define the minimum filesize for an individual file you expect to transfer.

  • max: Set the maximum filesize.

    With this option you can limit the filesize of a single file you transfer.

  • bytestring: Defines if a failure is returned with a userfriendly number, or with the plain filesize.

    With this option you can define if the user gets '10864' or '10MB'. Default value is true which returns '10MB'.

When only a string is given it is used as max. But you can also use the methods setMin() and setMax() to set both options afterwards and getMin() and getMax() to receive the actual set values.

The size itself is also accepted in SI notation as done by most operating systems. Instead of 20000 bytes you can just give 20kB. All units are converted by using 1024 as base value. The following Units are accepted: kB, MB, GB, TB, PB and EB. As mentioned you have to note that 1kB is equal to 1024 bytes.

Example 19.24. Using the Size validator

$upload = new Zend_File_Transfer();

// Limit the size of a file to 40000 bytes
$upload->addValidator('Size', false, 40000);

// Limit the size a given file to maximum 4MB and mimimum 10kB
// Additionally returns the plain number in case of an error
// instead of a userfriendly one
$upload->addValidator('Size',
                      false,
                      array('min' => '10kB',
                            'max' => '4MB',
                            'bytestring' => false));