How to delete cookies in Magento 2?
In magento you can delete cookies via Magento\Framework\Stdlib\CookieManagerInterface interface class.
You can delete cookie using cookiesdelete() function from CookieManagerInterface Interface.
If you have set the cookie using cookie’s $metadata property, You need to inject Magento\Framework\Stdlib\Cookie\CookieMetadataFactory factory in your class to delete the cookie.
You can delete cookie using cookiesdelete() function from CookieManagerInterface Interface.
If you have set the cookie using cookie’s $metadata property, You need to inject Magento\Framework\Stdlib\Cookie\CookieMetadataFactory factory in your class to delete the cookie.
<?php
namespace Itsmage\DeleteCookie\Model;
class Cookie
{
/**
* @var \Magento\Framework\Stdlib\CookieManagerInterface CookieManagerInterface
*/
private $cookieManager;
/**
* @var \Magento\Framework\Stdlib\Cookie\CookieMetadataFactory CookieMetadataFactory
*/
private $cookieMetadataFactory;
public function __construct(
\Magento\Framework\Stdlib\CookieManagerInterface $cookieManager,
\Magento\Framework\Stdlib\Cookie\CookieMetadataFactory $cookieMetadataFactory
) {
$this->cookieManager = $cookieManager;
$this->cookieMetadataFactory = $cookieMetadataFactory;
}
/** start with delete custom cookies */
public function cookiesdelete()
{
if ($this->cookieManager->getCookie('magecookies')) {
$metadata = $this->cookieMetadataFactory->createPublicCookieMetadata();
$metadata->setPath('/');
return $this->cookieManager->deleteCookie('magecookies',$metadata);
}
}
}
Comments
Post a Comment