7

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
  • 1
    How did you fix this? I am also getting the same issue. Commented Nov 21, 2017 at 8:50

2 Answers 2

10

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;
  }
5
  • Thanks @Amit, I have updated my question in accordance with your solution. Why form key changes when calling the form key with core/session? Commented Jun 8, 2016 at 11:53
  • But _validateFormKey() always redirect because posted form key is and one I get from core session is different. Commented Jun 8, 2016 at 12:12
  • Please check cookie and session at admin
    – Amit Bera
    Commented Jun 8, 2016 at 12:18
  • Would you be open to submit a PR here? github.com/OpenMage/magento-lts/issues/1287
    – snh_nl
    Commented Nov 14, 2020 at 13:10
  • which form (or block code) and controller are used here exactly?
    – snh_nl
    Commented Nov 14, 2020 at 13:10
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.

4
  • where to place that in which module ?
    – ephemeral
    Commented Feb 9, 2018 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. Commented Feb 12, 2018 at 17:16
  • Even after adding that, it shows invalid form key error often. Why? Commented Sep 17, 2019 at 10:20
  • Have you cleaned cache? Or, it could be some issue with session saving... Commented Sep 17, 2019 at 13:00

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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