Magento – Form Key Value in template and controller

controllersform-keyform-validationfrontendmagento-1.9.2.1

The following function is used to get the form key in templates with type hidden. My customerController.php does not validate the form key with the method _validateFormKey(). When I echo the following function in controller, Its value differ from the value that is posted in form.

 echo Mage::getSingleton('core/session')->getFormKey(); 

My question is

  1. How can I validate this form key?
  2. Why form key in template is different from the form key in Controller?

In my template file

<input type="hidden" name="form_key" value="<?php echo Mage::getSingleton('core/session')->getFormKey(); ?>" />

but in my controller,

echo $this->getRequest()->getParam('form_key'); // IZwYiobh1jmXLdBG

echo Mage::getSingleton('core/session')->getFormKey(); // DzMQebo8poku9ZKa

Best Answer

Pass form_key:

For Validate form key ,you need to send the form key with URL or as a hidden input.

If you send as URL parameter then the parameter name should be form_key/[keyValue].

If send as hidden field then you need to send as

 <input name="form_key" type="hidden" value="<?php echo Mage::getSingleton('core/session')->getFormKey() ?>" />

Validated form Key

For validated form key at controller you need to add below code:

 if (!$this->_validateFormKey()) {
  $this->_redirect('*/*');
  return;
  }