Why this zend example stops working when I add a hash to the form
I'm following this example开发者_Go百科 tutorial
project code: http://akrabat.com/wp-content/uploads/zf-tutorial-layoutform.zip
tutorial: http://akrabat.com/zend-framework/a-form-in-your-layout/
The project code runs as expected, until I add a hash element to the form. All I do is add this code in the form under application/forms/Signup.php
$hash = new Zend_Form_Element_Hash('hash');
$hash->setSalt('mysalt');
$this->addElement($hash);
This extra bit of code throws everything off. When I submit the form now, it gives me the error that the 2 tokens don't match.
Some troubleshooting:
- The problem is not the hash itself because it works fine in my other examples.
- I think has to do with how the request is being handled in this example, but not sure what the problem is exactly. I thought it had to do with the hop count, but when I edit Zend_Form_Element_Hash and changed the hop count from 1 to 100, I still got the same error.
That's the extent of troubleshooting I could think of at my level of expertise with Zend. So thought it's time to ask the big brains. I'm hoping someone can figure it out.
It works for you even after you've added the hash element to the form? If so, could you please upload your project and post as a separate answer.
All I did was add the code you posted and it worked fine. Where are you using this code? It sounds like something to do with your environment?
From: Zend_Form_Element_Hash
This element provides protection from CSRF attacks on forms, ensuring the data is submitted by the user session that generated the form and not by a rogue script. Protection is achieved by adding a hash element to a form and verifying it when the form is submitted.
The name of the hash element should be unique. We recommend using the salt option for the element- two hashes with same names and different salts would not collide:
$form->addElement('hash', 'no_csrf_foo', array('salt' => 'unique'));
You can set the salt later using the setSalt($salt) method.
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.
I will try:
$form->addElement('hash', 'unique_form_name', array('salt' => 'unique_salt'));
I do not see unique form/hash name in your code and this is why tokens do not mach.
精彩评论