开发者

How to use Zend_Form_Element_Hash?

开发者 https://www.devze.com 2022-12-09 06:22 出处:网络
Then I\'m trying to use Zend_Form_Element_Hash it regenerates a hash every request. In my code: // form

Then I'm trying to use Zend_Form_Element_Hash it regenerates a hash every request.

In my code:

 // form
 $this->addElement('hash', 'hihacker', array('salt' => 'thesal'));

Then I dumping $_SESSION I see a new value each page reload.

Then I send a form it reports an error "The token '28a5e0e2a50a3d4afaa654468fd29420' does not match the given token 'a64407cc11376dac1916d2101de90d29'", each time - new pair of tok开发者_开发百科ens


$form = new Form();
$form->addElement('hash', 'hihacker',
    array('salt' => 'YOUR TOO MUCH SALTY TEXT !!@@'));
if ($this->_request->isPost() && $form->isValid($this->_request->getPost())) {
    // Valid ! you are safe do what ever you want .
} else if (count($form->getErrors('request_token')) > 0) {

    ///get him to the error controller 
    $this->_forward('csrf-forbidden', 'error');
    return;
}

its working very well for me but double check your session setting

" Internally, the element stores a unique identifier using Zend_Session_Namespace, and checks for it at submission (checking that the TTL has not expired). The 'Identical' validator is then used to ensure the submitted hash matches the stored hash. The 'formHidden' view helper is used to render the element in the form. " form ZF docs


Zend_Form_Element_Hash is supposed to regenerate every request. What you're describing is your tokens going out of synch. This generally happens with multiple forms or with redirects/forwards.

If you're using ajax somewhere on the page you can put this in the controller action (near the end)

$form->hash->initCsrfToken();

$this->view->hash = $form->hash->getValue();

Then when you do the ajax call, just pull the token and replace the token on the form using a selector and .replaceWith(). This is how you deal with multiple forms as well

Otherwise you're probably either redirecting something or loading something twice and you should change the hop in the Zend library. The hop is how many times a token can be requested before it expires


Check that there is not a hidden redirect or forward somewhere in your script... the hash has a hop count of 1 so any redirect will make it expire.

FWIW i think there was a subtle bug in the hash a few versions of ZF ago. I got stuck on exactly the same problem, and hacked the code to make the hop count = 2. When I upgraded ZF this problem went away.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号