6

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
  • 1
    How did you fix this? I am also getting the same issue. – Anshu Mishra Nov 21 '17 at 8:50
9

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;
  }
  • Thanks @Amit, I have updated my question in accordance with your solution. Why form key changes when calling the form key with core/session? – saiid Jun 8 '16 at 11:53
  • But _validateFormKey() always redirect because posted form key is and one I get from core session is different. – saiid Jun 8 '16 at 12:12
  • Please check cookie and session at admin – Amit Bera Jun 8 '16 at 12:18
2

To get your form_key validated in Magento 2.1, you need to place

<?php / @noEscape / echo $block->getBlockHtml('formkey'); ?>

Right after your FORM tag and before all input elements, in your .phtml template file.

  • where to place that in which module ? – ephemeral Feb 9 '18 at 13:58
  • Add it in your template file, right after your opening <form> tag and before all input elements. It's the easiest way and works. – Iveta Allogenes Feb 12 '18 at 17:16
  • Even after adding that, it shows invalid form key error often. Why? – Kowsigan Atsayam 2 days ago
  • Have you cleaned cache? Or, it could be some issue with session saving... – Iveta Allogenes 2 days ago

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.