Site icon MageComp Blog

How to Set and Get Cookie in Magento 2?

How to Set and Get Cookie in Magento 2

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.

Steps to Set and Get Cookie 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'
        );
    }
}

Conclusion:

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!

Exit mobile version