How to set and get cookie in Magento 2?

Magento 2 You can add/set cookies and get/retrieve the cookie using Magento\Framework\Stdlib\CookieManagerInterface Interface.

By default, You can set the cookie using $_COOKIE with native PHP.

When you are following the coding standard in Magento 2, PHPMd displays the error for $_COOKIE is discouraged in Magento 2.

It’s a bad idea to directly use $_COOKIE in the code. You have to always go for a standard way.

Set a value in a public cookie with the given name /value pairing.

Public cookies can be accessed by JS. HttpOnly will be set to false by default for these cookies but can be changed to true.

I have created a Model class for setting/getting the cookie in Magento 2.

<?php
declare(strict_types=1);

namespace Rbj\CookieDemo\Model;

use Magento\Framework\Stdlib\Cookie\CookieMetadataFactory;
use Magento\Framework\Stdlib\CookieManagerInterface;

class Cookie
{
    public function __construct(
        private readonly CookieManagerInterface $cookieManager,
        private readonly CookieMetadataFactory $cookieMetadataFactory
    ) {
    }

    /** Set Custom Cookie using Magento 2 */
    public function setCustomCookie(): void
    {
        $publicCookieMetadata = $this->cookieMetadataFactory->createPublicCookieMetadata();
        $publicCookieMetadata->setDurationOneYear();
        $publicCookieMetadata->setPath('/');
        $publicCookieMetadata->setHttpOnly(false);

        $this->cookieManager->setPublicCookie(
            'magento2cookie',
            'Custom_Cookie_Value',
            $publicCookieMetadata
        );
    }

    /** Get Custom Cookie using Magento cookie function */
    public function getCustomCookie(): ?string
    {
        return $this->cookieManager->getCookie(
            'magento2cookie'
        );
    }
}

In the above function, setCustomCookie() method adds a cookie with the Cookie name magento2cookie, and the value is Custom_Cookie_Value.

You need to call the setCustomCookie() method from the above model class.

Set Cookie in Magento
Set-Cookie in Magento

We have also added extra data with the cookie.

Extra data will be stored with the cookie using Magento\Framework\Stdlib\Cookie\CookieMetadataFactory class.

setDurationOneYear() used to store our cookies within a year period. It’s time duration.

setPath() is used for the path of the domain.

setHttpOnly() used for boolean operation, Value is true or false. By default value is false. To prevent your store from Malware attacks, select Yes value.

You can fetch cookie value using the getCookie(COOKIE_KEY) method Where COOKIE_KEY is your cookie key.