How To

How to Add Form Key in phtml File in Magento 2

Hello Magento Friends,

In this blog, we will learn How to Add Form Key in phtml File in Magento 2.

Form key helps to prevent Cross-Site Request Forgery attack. This means an attacker encourages users to perform actions they don’t intend to. Using the form key in Magento 2, you can keep your site safe from CSRF (Cross-Site Request Forgery) attacks.

Let’s learn how to add a form key in Magento 2.

Steps to Add Form Key in phtml File in Magento 2:

Step 1: Create block file Index.php in the given path

app/code/Vendor/Extension/Block/Index/Index.php

Now add the code as given below

<?php
 
namespace Vendor\Extension\Block\Index;
use Magento\Framework\Data\Form\FormKey;
  
class Index extends \Magento\Framework\View\Element\Template
{
    public function __construct(\Magento\Catalog\Block\Product\Context $context, FormKey $formKey,array $data = [])
    {
        $this->formKey = $formKey;
        parent::__construct($context, $data); 
    }
    protected function _prepareLayout()
    {
        return parent::_prepareLayout();
    }
    public function getFormKey()
    {
        return $this->formKey->getFormKey();
    }
}

Step 2: Create layout file customer_index_index.xml at the below path

app/code/Vendor/Extension/view/frontend/layout/ customer_index_index.xml

And embed the below code

<?xml version="1.0"?>
 
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
 
    <head>
        <title>Customer Contact Form</title>
    </head>
    <body> 
        <referenceContainer name="content">
            <block class="Vendor\Extension\Block\Index\Index" template="Vendor_Extension::customer.phtml"/>
        </referenceContainer>
    </body>
</page>

Step 3: Create a customer.phtml file at the following path

app/code/Vendor/Extension/view/frontend/templates/customer.phtml

Now add the below-mentioned code

<!-- here use your controller path in form action  -->
<form  enctype="multipart/form-data" action="<?php echo $block->getBaseUrl().'customer/index/post/';?>" name="customemaildata" method="post" id="contactForm-1" data-hasrequired="<?php echo __('* Required Fields') ?>" data-mage-init='{"validation":{}}'>
    
    <fieldset class="fieldset">
        <input name="form_key" type="hidden" value="<?php echo $block->getFormKey();?>">
            <div class="field email required">
                <label class="label" for="email">Name :-</label>
                <div class="control">
                    <input name="name" id="name"  class="input-text" type="text" data-validate="{required:true}"/>
                </div>
            </div>
            
            <div class="field email required">
                <label class="label" for="email">Email:-</label>
                <div class="control">
                    <input name="email" id="email"  class="input-text" type="email" data-validate="{required:true, 'validate-email':true}"/>
                </div>
            </div>  
                              
    </fieldset>
    <div class="actions-toolbar">
        <div class="primary">
            <input type="hidden" name="hideit" id="hideit" value="" />
            <button type="submit" title="<?php echo __('Submit') ?>" class="action submit primary">
                <span><?php echo __('Submit') ?></span>
            </button>
        </div>
    </div>
</form>

The input tag will return with the form as given below. You can use this key based on your requirement.

<input name="form_key" type="hidden" value="u4b7uLozXoFaA6br">

Conclusion:

Using the above steps, you can easily add form key in phtml file in Magento 2. To add advanced security to your Magento 2 store, avail of Magento Security Patches Installation Service and safeguard your store from vulnerabilities.

Share the article with other Magento merchants, and stay with us!

Happy Coding!

Click to rate this post!
[Total: 2 Average: 5]
Dhiren Vasoya

Dhiren Vasoya is a Director and Co-founder at MageComp, Passionate ?️ Certified Magento Developer?‍?. He has more than 9 years of experience in Magento Development and completed 850+ projects to solve the most important E-commerce challenges. He is fond❤️ of coding and if he is not busy developing then you can find him at the cricket ground, hitting boundaries.?

Recent Posts

Generating Thumbnails with Spatie Media Library in Laravel 11: A Step-by-Step Guide

Generating image thumbnails is a common requirement in web applications, especially when handling media-heavy content.…

7 hours ago

Enhancing Web Application Security with Laravel’s Built-In Features

In today’s digital landscape, web application security is paramount. As a powerful PHP framework, Laravel…

1 day ago

Magento 2 Extensions Digest October 2024 (New Release & Updates)

October was an exciting month for MageComp! From significant updates across our Magento 2 extension…

1 day ago

Improving Error Handling and Transition Management in Remix with useRouteError and useViewTransitionState

In modern web development, seamless navigation and state management are crucial for delivering a smooth…

1 week ago

Magento Open Source 2.4.8-Beta Release Notes

Magento Open Source 2.4.8 beta version released on October  8, 2024. The latest release of…

1 week ago

How to Create Catalog Price Rule in Magento 2 Programmatically?

Hello Magento Friends, Creating catalog price rules programmatically in Magento 2 can be a valuable…

2 weeks ago