In the vast world of e-commerce, providing a seamless and personalized shopping experience is crucial for attracting and retaining customers. One of the tools at a developer’s disposal for achieving this is cookies. In Magento 2, a leading e-commerce platform, cookies play a significant role in storing session information, user preferences, and other essential data. In this article, we will explore how to effectively manage cookies in Magento 2 by learning how to set, get, and delete them from the article Magento2 get set delete cookie.

You may be interested in Magento1 article: Mastering Cookie Management in Magento: Setting, Getting, and Deleting Cookies

Setting Cookies in Magento 2 with PHP:

Setting cookies in Magento 2 via PHP is facilitated by the \Magento\Framework\Stdlib\CookieManagerInterface interface. Below is a straightforward example illustrating how to set a cookie:

// Use necessary namespaces and declare the class

public function setCookie()
{
    $cookieValue = 'example_cookie_value';
    $cookieName = 'example_cookie_name';
    $this->cookieManager->setPublicCookie($cookieName, $cookieValue);
}

Getting Cookies in Magento 2 with PHP:

Retrieving cookies in Magento 2 via PHP follows a similar pattern using the \Magento\Framework\Stdlib\CookieManagerInterface interface. Here’s how you can retrieve a cookie’s value:

// Use necessary namespaces and declare the class

public function getCookieValue($cookieName)
{
    return $this->cookieManager->getCookie($cookieName);
}

Deleting Cookies in Magento 2 with PHP:

Deleting cookies in Magento 2 via PHP involves setting the cookie’s expiration time in the past. Here’s a method to delete a cookie:

// Use necessary namespaces and declare the class

public function deleteCookie($cookieName)
{
    $this->cookieManager->deleteCookie($cookieName);
}

complete code for Set, get and delete data from cookie in magento 2

<?php
/**
 * Copyright © https://www.jyotiranjan.in/ All rights reserved.
 * See COPYING.txt for license details.
 */
declare(strict_types=1);

namespace Jrb\DemoModule\Helper;

use Magento\Framework\App\Helper\AbstractHelper;

class ManageCookie extends AbstractHelper
{
    /**
    * @var \Magento\Framework\Stdlib\CookieManagerInterface
    */
    protected $_cookieManager;

    /**
    * @var \Magento\Framework\Stdlib\Cookie\CookieMetadataFactory
    */
    protected $_cookieMetadataFactory;

    /**
     * @param \Magento\Framework\App\Helper\Context $context
     */
    public function __construct(
        \Magento\Framework\App\Helper\Context $context,
        \Magento\Framework\Stdlib\CookieManagerInterface $cookieManager,
        \Magento\Framework\Stdlib\Cookie\CookieMetadataFactory $cookieMetadataFactory
    ) {
        parent::__construct($context);
        $this->_cookieManager = $cookieManager;
        $this->_cookieMetadataFactory = $cookieMetadataFactory;
    }

    /**
     * create custom cookie
     */
    public function createCookie($name, $value, $duration = 86400){
        $metadata = $this->_cookieMetadataFactory
            ->createPublicCookieMetadata()
            ->setSecure(false)
            ->setHttpOnly(false)
            ->setDuration($duration);
        $this->_cookieManager->setPublicCookie(
            $name,
            $value,
            $metadata
        );
    }

    /**
     * read/get custom cookie by name
     */
    public function readCookie($name){
        return $this->_cookieManager->getCookie($name);
    }

    /**
     * remove/delete custom cookie by name
     */
    public function removeCookie($name){
        $this->_cookieManager->deleteCookie($name);
    }
}

Managing Cookies in Magento 2 with JavaScript:

While PHP handles server-side cookie operations, JavaScript empowers developers with client-side manipulation capabilities, enriching the user experience further. Below is a JavaScript snippet demonstrating how to manage cookies:

<script type="text/javascript">
    define([
        'jquery',
        'mage/cookies'
    ], function ($) {
        // Get cookie value
        $.cookie('cookie_name');
        // Set cookie value
        $.cookie('cookie_name', cookievalue);
        // Set cookie value with expiry
        $.cookie('cookie_name', 'value', { expires: 7, path: '/' });
        // Delete cookie value
        $.cookie('cookie_name', 'value', { expires: -1, path: '/' });
    });
</script>

Conclusion:

In Magento 2, cookies play a pivotal role in maintaining session information and delivering personalized experiences to users. By mastering the techniques of setting, getting, and deleting cookies, developers can elevate the functionality and user experience of their Magento 2 stores. From retaining user preferences to efficiently managing shopping carts, cookies serve as indispensable tools in shaping the e-commerce landscape. A comprehensive understanding of cookie management empowers developers to craft dynamic and engaging online shopping experiences for customers, ensuring long-term success in the competitive e-commerce market.

Magento2 get set delete cookie
Tagged on:     

One thought on “Magento2 get set delete cookie

Leave a Reply

Your email address will not be published. Required fields are marked *