Magento 2 - What is the use of formkey

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.


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