A free and open-source book on ZF3 for beginners


10.4. Validating Uploaded Files

Uploaded files need to be checked for correctness as any other form data. For example, you may need to check that:

For doing the checks like above, ZF3 provides a number of useful file validators (listed in table 10.1). Those validator classes belong to Zend\Validator component and live in Zend\Validator\File namespace.

Table 10.1. Standard File Validators
Class name Short alias Description
Count FileCount Checks whether the file count is in a given range (min, max).
WordCount FileWordCount Calculates the number of words in a file and checks whether it lies in a given range.
Upload FileUpload Performs security checks ensuring that all given files were really uploaded through HTTP POST and there were no upload errors.
UploadFile FileUploadFile Performs security checks ensuring that a file really was uploaded through HTTP POST and there were no upload errors.
Size FileSize Checks whether the file size lies in a given range.
FilesSize FileFilesSize Checks that the summary size of all given files lies in a given range.
Extension FileExtension Checks that the extension of a file belongs to a set of allowed extensions.
ExcludeExtension FileExcludeExtension Checks that the extension of a file DOES NOT belong to a set of extensions.
MimeType FileMimeType Checks that the MIME type of a file belongs to the list of allowed MIME types.
ExcludeMimeType FileExcludeMimeType Checks that the MIME type of a file DOES NOT belong to the list of MIME types.
IsImage FileIsImage Checks that the file is a graphical image (JPEG, PNG, GIF, etc.)
ImageSize FileImageSize Checks that the image file's dimensions lie in a given range.
Exists FileExists Checks whether the file exists on disk.
NotExists FileNotExists Checks whether the file doesn't exist on disk.
IsCompressed FileIsCompressed Checks that the file is an archive (ZIP, TAR, etc.)
Hash FileHash Checks that the file content matches the given hash(es).
Crc32 FileCrc32 Checks that the file content has the given CRC32 check sum.
Sha1 FileSha1 Checks that the file content has the given SHA-1 hash.
Md5 FileMd5 Checks that the file content has the given MD5 hash.

As you can see from the table above, file validators may be roughly divided in the following groups:

42) A file hash is used for checking file data integrity (for example, to ensure that file data is not corrupted). There are several hash algorithms available (MD5, SHA-1, CRC32, etc.)

Please note that since file validators live in Zend\Validator\File namespace, their short aliases (that you use when creating a validator with the factory) start with File prefix. For example, the IsImage validator has FileIsImage alias.

We will show how to use some of these file validators in the Image Gallery code example later in this chapter.


Top