In this editorial, we will learn how to set, get and delete cookie in Magento 2.
In core PHP we set cookie by following function.
setcookie(‘logged_in’, ‘false’, time() – (86400 * 30), “/”);
but in magento this will generate coding standard issue. I already add $_FILES superglobal function issue and solution.
Issue will be generated “The use of function setcookie() is discouraged“.

So Magento provides some classes and method to solve issue You can check Magento doc also for Cookie.
<?php
namespace Namespace\Module\FileName;
public const COOKIE_NAME = 'my_cookie';
/**
* @var \Magento\Framework\Stdlib\CookieManagerInterface CookieManagerInterface
*/
private $cookieManager;
/**
* @var \Magento\Framework\Stdlib\Cookie\CookieMetadataFactory CookieMetadataFactory
*/
private $cookieMetadataFactory;
/**
* Constructor
*
* @param \Magento\Framework\Stdlib\CookieManagerInterface $cookieManager
* @param \Magento\Framework\Stdlib\Cookie\CookieMetadataFactory $cookieMetadataFactory
@param \Magento\Framework\Stdlib\Cookie\PhpCookieManager $phpCookieManager
*/
public function __construct(
\Magento\Framework\Stdlib\CookieManagerInterface $cookieManager,
\Magento\Framework\Stdlib\Cookie\CookieMetadataFactory $cookieMetadataFactory,
\Magento\Framework\Stdlib\Cookie\PhpCookieManager $phpCookieManager
) {
$this->cookieManager = $cookieManager;
$this->cookieMetadataFactory = $cookieMetadataFactory;
$this->phpCookieManager = $phpCookieManager;
}
/** Set Custom Cookie using Magento 2 */
public function setMyCookie()
{
$publicCookieMetadata = $this->cookieMetadataFactory->createPublicCookieMetadata();
$publicCookieMetadata->setDurationOneYear(); //add this line if you want to add cookie for one year
$publicCookieMetadata->setPath('/');
$publicCookieMetadata->setHttpOnly(false);
$publicCookieMetadata->setSameSite('Strict');
return $this->cookieManager->setPublicCookie(
self::COOKIE_NAME,
time() - (86400 * 30),
$publicCookieMetadata
);
}
/** Get Custom Cookie using */
public function getMyCookie()
{
return $this->cookieManager->getCookie(
self::COOKIE_NAME
);
}
/** delete Custom Cookie using */
public function deleteMyCookie()
{
$metaData = $this->cookieMetadataFactory->createPublicCookieMetadata();
$metaData->setPath('/')->setDuration(-1);
$this->phpCookieManager->setPublicCookie(
self::COOKIE_NAME,
'',
$metaData
);
return $this;
}
You can delete cookie in another way also so I add below another method.
public function deleteMyCookie()
{
if ($this->cookieManager->getCookie(self::COOKIE_NAME)) {
$metadata = $this->cookieMetadataFactory->createCookieMetadata();
$metadata->setPath('/');
$this->cookieManager->deleteCookie(self::COOKIE_NAME, $metadata);
}
}
I hope this article is simple to grasp.
If you still have any issue feel free to ask and let me know your views to make the better. Share this solution with your other Magento buddies via social media.
Thanks for reading.