Hello Magento Friends,
In today’s blog, we will learn about How to Set and Get Cookie in Magento 2?
Cookies are small files on a user’s computer that are usually used to identify a user. Cookies are used to track users and provide a personalized experience. You can set, update, and retrieve cookie. In Magento 2 you can easily set and get cookie data in Magento 2.
Step 1: Create a Customcookie.php file at the below path
app\code\Vendor\Extension\Model
And add the code as follows
<?php namespace Vendor\Extension\Model; class Customcookie { private $customCookieManager; private $customCookieMetadataFactory; public function __construct( \Magento\Framework\Stdlib\CookieManagerInterface $customCookieManager, \Magento\Framework\Stdlib\Cookie\CookieMetadataFactory $customCookieMetadataFactory) { $this->customCookieManager = $customCookieManager; $this->customCookieMetadataFactory = $customCookieMetadataFactory; } public function setCookie() { $customCookieMetadata = $this->customCookieMetadataFactory->createPublicCookieMetadata(); $customCookieMetadata->setDurationOneYear(); $customCookieMetadata->setPath('/'); $customCookieMetadata->setHttpOnly(false); return $this->customCookieManager->setPublicCookie( 'customcookie', 'Cookie_Value', $customCookieMetadata ); } public function getCookie() { return $this->customCookieManager->getCookie( 'customcookie' ); } }
Using the above method, you can easily set and get cookie data in Magento 2. Inform your users if your site uses cookies and take consent from them with the help of Cookie Compliance Extension for Magento 2. If you have any doubts, share them with me through the comment section. Also, share the article with your friends to help them work with cookie values.
Happy Coding!
In the world of business, understanding financial metrics is crucial for making informed decisions and…
Welcome to the MageComp Monthly Digest, where we bring you the latest updates, releases, and…
In this era, businesses are always on the lookout for ways to engage with their…
Managing a Shopify store efficiently involves keeping your product catalog organized. This includes removing outdated…
E-commerce has transformed the way consumers shop for products and services and interact with businesses.…
The e-commerce world is constantly in flux. New tech and strategies emerge daily to help…