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

Five Essential Payroll Compliance Tips for eCommerce Startups

Are you setting up a payroll system for your eCommerce startup? Ensuring compliance with myriad…

12 hours ago

Optimizing Laravel Blade: Unlocking Advanced Fetcher Techniques

In the expansive universe of Laravel development, Blade serves as the stellar templating engine, propelling…

13 hours ago

Magento 2: Add Quantity Increment and Decrement on Category Page

Hello Magento Friends, In this blog, we will discuss about adding quantity increment and decrement…

2 days ago

How to Integrate ChatGPT with Laravel Application?

In this guide, we'll explore how to integrate ChatGPT, an AI-powered chatbot, with a Laravel…

6 days ago

What are Net Sales? How to Calculate Your Net Sales?

In the world of business, understanding financial metrics is crucial for making informed decisions and…

1 week ago

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

Welcome to the MageComp Monthly Digest, where we bring you the latest updates, releases, and…

1 week ago