How to set and get cookie in Magento 2?

Magento 2 You can add/set cookie 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 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 set/gets the cookie in Magento 2.

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

You need to call 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 cookie withing one year period. Its time duration.

setPath() 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 getCookie(COOKIE_KEY) method Where COOKIE_KEY is your cookie key.