0

I want to delete cookies programmatically before as login customer.

0

Overview of using cookie in Magento 2 Step 1: Create a controller to read cookie Step 2: Create a controller to delete cookie Step 1: Create a controller to read cookie The first is setting a Readcookie.php controller in the app/code/Mageplaza/HelloWorld/Controller/Cookie. The Readcookie.php contains the following content:

<?php
namespace Mageplaza\HelloWorld\Controller\Cookie;
class Readcookie extends \Magento\Framework\App\Action\Action
{
/**
* @var \Magento\Framework\Stdlib\CookieManagerInterface
*/
protected $_cookieManager;
/**
* @param \Magento\Framework\App\Action\Context $context
* @param \Magento\Framework\Stdlib\CookieManagerInterface $cookieManager
*/
public function __construct(
     \Magento\Framework\App\Action\Context $context,
     \Magento\Framework\Stdlib\CookieManagerInterface $cookieManager
)
{
     $this->_cookieManager = $cookieManager;
     parent::__construct($context);
}
public function execute()
{
     $cookieValue = $this->_cookieManager->getCookie(\Mageplaza\HelloWorld\Controller\Cookie\Addcookie::COOKIE_NAME);
     echo($cookieValue);
}
}

Step 2: Create a controller to delete cookie Create the Deletecookie controller in the app/code/Mageplaza/HelloWorld/Controller/Cookie with the following content:

<?php
namespace Mageplaza\HelloWorld\Controller\Cookie;
class Deletecookie extends \Magento\Framework\App\Action\Action
{
/**
* @var \Magento\Framework\Stdlib\CookieManagerInterface
*/
protected $_cookieManager;
/**
* @param \Magento\Framework\App\Action\Context $context
* @param \Magento\Framework\Stdlib\CookieManagerInterface $cookieManager
*/
public function __construct(
     \Magento\Framework\App\Action\Context $context,
     \Magento\Framework\Stdlib\CookieManagerInterface $cookieManager
)
{
     $this->_cookieManager = $cookieManager;
     parent::__construct($context);
}
public function execute()
{
     $this->_cookieManager->deleteCookie(
         \Mageplaza\HelloWorld\Controller\Cookie\Addcookie::COOKIE_NAME
     );
     echo('DELETED');
}
}

And now, you can enable the cookie on your Magento 2 store. If you have any trouble in tracking the topic, leave a comment to ask for the help. Good luck to you!

  • I will check and update you soon. – Masud Shaikh Nov 16 '18 at 10:21
  • I can't understand this line $cookieValue = $this->_cookieManager->getCookie(\Mageplaza\HelloWorld\Controller\Cookie\Addcookie::COOKIE_NAME); – Masud Shaikh Nov 16 '18 at 13:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.