Determine file hash before using with zend validate md5

73 views Asked by At

Here is the code provided on the manual:

// Does file have the given hash?
$validator = new \Zend\Validator\File\Md5('3b3652f336522365223');

I'm not quite understanding how to use this as a file validator inside my Zend Form. How do I prepopulate the hash when the file has not been uploaded yet?

2

There are 2 answers

0
MatsLindh On

You don't. The hash validator is to ensure that the uploaded file has a provided hash. I.e. that you already know the hash of the file (either that the file has been uploaded earlier, you've gotten the hash from a 3rd party, or the expected hash of the file was included in the request), and want to verify that the file that were uploaded has the same hash.

See for example How to calculate the MD5 hash of a file using javascript for how to provide the expected MD5 hash together with the uploaded file to validate that the file was uploaded correctly.

The question then becomes what the problem you're trying to solve is - most servers will cancel the request if the request is aborted while the file is being uploaded (so an incomplete file will usually not be handed to your code).

0
yivi On

A \Zend\Validator\File\Md5, generally speaking, wouldn't be very useful in a webform.

Either the user has to provide the MD5 hash on a separate field, or you have to calculate it dynamically via javascript before the form is submitted. And on either case, you can't really use to "validate" the file, since you would either depend on the file to provide the validation hash, and it's useless to verify the upload completed (if the upload fails, the request will be aborted and you wont have access to the incomplete file).

You could probably use to validate some sort of server initiated download. E.g. somewhere in your code you've download a file, and somewhere separately you get access to the hash of the file you are going to download: you can then use \Zend\Validator\File\Md5 to validate the authenticity/integrity.

E.g.:

$file_path = '/downloads/file.tgz';
$fp = fopen ($file_path, 'w');
$url = "http://remotehost/file.tgz";

$ch = curl_init($url);

curl_setopt($ch, CURLOPT_TIMEOUT, 50);
curl_setopt($ch, CURLOPT_FILE, $fp);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);

$data = curl_exec($ch);
curl_close($ch);

// either you get the hash with a different request, or you've somehow obtained the hash previously
$validator = new \Zend\Validator\File\Md5($hash);

if (! $validator->isValid($file_path)) {
// file isn't valid, do something about it

}