I see this line of code inside the login form.
<?php echo $block->getBlockHtml('formkey'); ?>
- What is the use of it?
- Is it more secure?
- Is it a must for form post?
Form keys in Magento are a means of preventing against Cross Site Request Forgery, in short, it's to keep you safe from people trying to post to your forms (like add to cart) from other sites posing as you.
This can be dangerous because someone could theoretically create their own form and post to any form handler controller action in your store. CSRF protection essentially ignores any post which fail a check on the included form_key parameter with the form post.
<?php echo $this->getBlockHtml('formkey')?>
It tells Magento to look for a layout block with the name "formkey" and output it. In Magento this is usually some file which has this in it:
<div><input name="form_key" type="hidden" value="<?php echo Mage::getSingleton('core/session')->getFormKey() ?>" /></div>
This instructs Magento to output and store a unique form key for a user session. All CSRF-protected Magento controller actions will verify against this before doing anything of value.
\Magento\Framework\Data\Form\FormKey\Validator
.
Commented
Aug 1, 2017 at 21:15
You can add formkey by this code:
<?php
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$FormKey = $objectManager->get('Magento\Framework\Data\Form\FormKey');
?>
//Hidden form key field after <form> tag
<input name="form_key" type="hidden" value="<?php echo $FormKey->getFormKey();?>">
If you want to add form key in phtml file then use direct
$this->getFormKey()
<input name="form_key" type="hidden" value="<?php echo $block->getFormKey();?>">
Using Dependency Injection in your class constructor:
protected $formKey;
public function __construct(
\Magento\Framework\Data\Form\FormKey $formKey
) {
$this->formKey = $formKey;
}
public function getFormKey()
{
return $this->formKey->getFormKey();
}
Note: Don't use object manager directly in phtml files
ObjectManager
use in frontend this is not a good practice .
Commented
Jul 4, 2018 at 8:04
There is no need of initialising object manager and all, you can do it in two ways
By using below javscript statement in your phtml view file.
window.FORM_KEY
By calling core block class getKey method in your phtml template file:
$block->getKey()
Hope this helps!
Thanks