How to Create/Get/Update/Delete Cookie in Magento 2
Vinh Jacker | 12-18-2024
In Magento 2 as well as other eCommerce platforms, using cookies is the familiar way to achieve the data. Now, we will dig deeper to understand how to use cookies in Magento 2.
What are Cookies?
Cookies is a type of document that is used to save all information on the browser. Namely, when a user visits your website and leaves some personal info, the cookies allows showing those data if he is back in the next time. With the cookies, you may be confident to enhance the customer shopping experience.
So, what do you need to follow in order to use the cookies in Magento 2?
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);
}
}
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!
Related Topics