4

Can anyone please tell me how to set and get cookie on a phtml file in magento 2?? I don't want to create or use any extension for this.

7

Try it.


$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$cookieManager = $objectManager->get('Magento\Framework\Stdlib\CookieManagerInterface');

// set cookie value
$cookieManager->setPublicCookie('custome1', 'custome1');

//get cookie value
$cookieManager->getCookie('custome1');

  • Thank you for your help. But this not worked. – Asish Hira Mar 16 '16 at 8:14
  • 1
    refresh 2 times your page. – Sohel Rana Mar 16 '16 at 8:50
4

Magento 2 cookie will not work when cache is enabled. You have to make your phtml file uncacheable.

Use cacheable="false" property in your xml.

<block class="Magento\Framework\View\Element\Template" name="custom.file" template="Vendor_Module::custom.phtml" cacheable="false"/>

Now You can use cookie manager in your phtml file.

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$cookieManager = $objectManager->get('Magento\Framework\Stdlib\CookieManagerInterface');

// Set cookie
$cookieManager->setPublicCookie('cookiename', 'cookievalue');

// Get cookie
$cookieManager->getCookie('cookiename');

// Delete cookie
$cookieManager->deleteCookie('cookiename');

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.