February 27, 2012

How to write a custom Zend validator to check the hash of a file against a database record

Question by blainarmstrong

I’m building a file repository where each file has a database entry associated with it. In that database, I include the sha1 hash value for the file. Also, for security reasons, I rename each file with a specific pattern, so I can’t check the filename directly via the form’s filename value.

I’m trying to prevent people from uploading the same file twice, so I want to create a form validator that takes the file being uploaded and checks the hash of the file against all the values in the database. If the hash is already in the database–and thus the file already exists–the validator should return false. How access the file from inside the validator class so I can calculate the hash?

Answer by Starx

Your question is very badly asked. So I will not dig into the logic of it.Sorry Here is a very simple example of how you can create a Custom Validation Class.

The most important thing you need to remember is two methods.

  1. isValid(): Returns either true or false through a logic
  2. getMessages(): Returns errors messages in case of invalid.

Here is a basic example of comparing whether a user is admin or not.

class CustomValidate_UserAdmin extends Zend_Validate_Abstract
{
    $admin = "username"; //I am using a static value this time

    protected $_messageTemplates = array(
        self::FLOAT => "'%value%' is not an admin"
    );

    public function isValid($value)
    {
        $this->_setValue($value);

        if($this -> admin == $value) {     
             return true;
        }
    }
}

Now use it

$element->addValidator(new CustomValidate_UserAdmin('username'));

This is a very simple example to understand. You can replace it with your logic with a lot of ease I think.

Updates


Add validation like this…

$element->addValidator(new CustomValidate_Hash('file/location', $hashvaluettocompare));

Now in your validation class

function isValid($location, $value) {
   if(hash_file("md5", $location)==$value) return true;
}

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!