10

I need to set a value to the cookie in a phtml file and I need to get it's value in another phtml file.

Is it possible to set and get the values using jQuery?

3 Answers 3

9

Create Cookie

We will be creating a test controller to create

app/code/[Name_Space]/[Your_Module]/Controller/Cookie/Addcookie.php

<?php
namespace [Name_Space]\[Your_Module]\Controller\Cookie;
class Addcookie extends \Magento\Framework\App\Action\Action
{
const COOKIE_NAME = 'test';
const COOKIE_DURATION = 86400; // lifetime in seconds
/**
* @var \Magento\Framework\Stdlib\CookieManagerInterface
*/
protected $_cookieManager;
/**
* @var \Magento\Framework\Stdlib\Cookie\CookieMetadataFactory
*/
protected $_cookieMetadataFactory;
/**
* @param \Magento\Framework\App\Action\Context $context
* @param \Magento\Framework\Stdlib\CookieManagerInterface $cookieManager
* @param \Magento\Framework\Stdlib\Cookie\CookieMetadataFactory $cookieMetadataFactory
*/
public function __construct(
     \Magento\Framework\App\Action\Context $context,
     \Magento\Framework\Stdlib\CookieManagerInterface $cookieManager,
     \Magento\Framework\Stdlib\Cookie\CookieMetadataFactory $cookieMetadataFactory
)
{
     $this->_cookieManager = $cookieManager;
     $this->_cookieMetadataFactory = $cookieMetadataFactory;
     parent::__construct($context);
}
public function execute()
{
     $metadata = $this->_cookieMetadataFactory
         ->createPublicCookieMetadata()
         ->setDuration(self::COOKIE_DURATION);
     $this->_cookieManager->setPublicCookie(
         self::COOKIE_NAME,
         'YOUR COOKIE VALUE',
         $metadata
     );
     echo('Create Cookie');
}
}

Read Cookie

We will create a Readcookie.php controller to read cookie

app/code/[Name_Space]/[Your_Module]/Controller/Cookie

<?php
namespace [Name_Space]\[Your_Module]\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(\[Name_Space]\[Your_Module]\Controller\Cookie\Addcookie::COOKIE_NAME);
     echo($cookieValue);
}
}

Delete Cookie

We will create a Deletecookie.php controller to create cookie

app/code/[Name_Space]/[Your_Module]/Controller/Cookie

<?php
namespace [Name_Space]\[Your_Module]\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(
         \[Name_Space]\[Your_Module]\Controller\Cookie\Addcookie::COOKIE_NAME
     );
     echo('DELETED');
}
}

The 3 steps I mention above is the shortest process for you to Use Cookie in Magento 2. With this guide, you can manage the Cookie in Magento 2 easily.

2
  • Hello it's not working on magento2.3 versions Jan 5, 2021 at 16:34
  • 1
    In the metadata you need to specify both path and domain. for example : $this->_cookieMetadataFactory ->createPublicCookieMetadata() ->setDuration(self::COOKIE_DURATION) ->setPath($this->_sessionManager->getCookiePath()) ->setDomain($this->_sessionManager->getCookieDomain()); Jun 17, 2021 at 16:58
5

Set the cookies

<script>
    require([
        'jquery',
        'mage/cookies'
    ], function ($) {
       $.cookie('cookie_name', 'value', { path: '/' });//Set the cookies
    });
</script>

If you want to get the value from another page, notice the path setting { path: '/' }!

Because cookies are only accessible to the specified path and any subpaths, more discussion about this you could see here Cookie path and its accessibility to subfolder pages.

Get the cookies

<script>
    require([
        'jquery',
        'mage/cookies'
    ], function ($) {
        var temp = $.cookie('cookie_name');//Get the cookies
    });
</script>
1
<script>
    require(
        [ 'jquery'],function($){
            //set cookie
            $.cookie('customname', 'customvalue', { expires: 365, path: '/' });

            //get cookie
            getCookieValue(customname)
        });

        function getCookieValue(cookiename) {
                var name = cookiename + "=";
                var cookieSplit = document.cookie.split(';');
                for(var i = 0; i <cookieSplit.length; i++) {
                    var a = cookieSplit[i];
                    while (a.charAt(0)==' ') {
                        a = a.substring(1);
                    }
                    if (a.indexOf(name) == 0) {
                        return a.substring(name.length,a.length);
                    }
                }
                return "";
            }
</script>
6
  • i need to get the cookie value in another phtml page. how it gets?
    – Rita Jose
    Jun 2, 2017 at 11:24
  • You can same as above just remove $.cookie() line Jun 2, 2017 at 11:27
  • Have you try with above code? Jun 2, 2017 at 11:55
  • yeah, i didn't get the answer.
    – Rita Jose
    Jun 2, 2017 at 11:58
  • whats the issue have you faced? Jun 2, 2017 at 11:59

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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