19

I want to add a COOKIE with value and some duration, how to do it in magento 2.

Thanks

2 Answers 2

32

IMO the best approach would be to create a class to wrap the cookie creation and then just use it where you want.

The Cookie Class

{Vendor}/{Module}/Cookie/Example.php

<?php 

namespace Vendor\Module\Cookie;

use Magento\Framework\Stdlib\CookieManagerInterface;
use Magento\Framework\Stdlib\Cookie\CookieMetadataFactory;
use Magento\Framework\Session\SessionManagerInterface;

class Example
{
    /**
     * Name of cookie that holds private content version
     */
    const COOKIE_NAME = 'example';

    /**
     * CookieManager
     *
     * @var CookieManagerInterface
     */
    private $cookieManager;

    /**
     * @var CookieMetadataFactory
     */
    private $cookieMetadataFactory;

    /**
     * @var SessionManagerInterface
     */
    private $sessionManager;

    /**
     * @param CookieManagerInterface $cookieManager
     * @param CookieMetadataFactory $cookieMetadataFactory
     * @param SessionManagerInterface $sessionManager
     */
    public function __construct(
        CookieManagerInterface $cookieManager,
        CookieMetadataFactory $cookieMetadataFactory,
        SessionManagerInterface $sessionManager
    ) {
        $this->cookieManager = $cookieManager;
        $this->cookieMetadataFactory = $cookieMetadataFactory;
        $this->sessionManager = $sessionManager;
    }

    /**
     * Get form key cookie
     *
     * @return string
     */
    public function get()
    {
        return $this->cookieManager->getCookie(self::COOKIE_NAME);
    }

    /**
     * @param string $value
     * @param int $duration
     * @return void
     */
    public function set($value, $duration = 86400)
    {
        $metadata = $this->cookieMetadataFactory
            ->createPublicCookieMetadata()
            ->setDuration($duration)
            ->setPath($this->sessionManager->getCookiePath())
            ->setDomain($this->sessionManager->getCookieDomain());

        $this->cookieManager->setPublicCookie(
            self::COOKIE_NAME,
            $value,
            $metadata
        );
    }

    /**
     * @return void
     */
    public function delete()
    {
        $metadata = $this->cookieMetadataFactory
            ->createPublicCookieMetadata()
            ->setDuration(0)
            ->setPath($this->sessionManager->getCookiePath())
            ->setDomain($this->sessionManager->getCookieDomain());

        $this->cookieManager->deleteCookie(
            self::COOKIE_NAME,
            $metadata
        );
    }
}

This example was based on Magento\Framework\App\PageCache\FormKey and represent a single cookie with name "example"

If you want to add some custom properties to the $metadata (PublicCookieMetadata) as change the path,http_only, etc you should refactor the set() and/or delete() method(s).

How to use it

You can access that class simply using the Object Manager in almost anywhere (Ugly Approach):

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$objectManager->get('Vendor\Module\Cookie\Example')
    ->set('value', 3600);

Depending "where" you need to create the cookie you can take a look at the constructor of your class maybe you already have an Object manager there, if not you can also inject it in the constructor.

10
  • @J. John, Hey! i juts saw that you accept the answer while i've been editing it, just take a look now, because i made several changes in order to simplify the implementation. Commented Feb 3, 2016 at 6:03
  • 3
    I've to edit createCookieMetaData() to createPublicCookieMetadata() in set method to resolve the error (fatal error). Smart approach though!
    – R T
    Commented Apr 12, 2016 at 10:39
  • what's the difference between Magento\Framework\Session\SessionManagerInterface used by you and Magento\Framework\Session\Config\ConfigInterface used in Magento\Framework\Session\SessionManager?
    – LucScu
    Commented Jun 1, 2016 at 8:17
  • @MauroNigrele function call in set and delete method should be createPublicCookieMetadata instead of createCookieMetadata
    – Shivam
    Commented Jun 9, 2016 at 6:24
  • 1
    Guys. I've proposed changes because $this->createPublicCookieMetadata() doesn't exist in this class. It should be $this->cookieMetadataFactory->createPublicCookieMetadata() See in magento repo. But I've get 2 rejects. LOL...
    – spiilmusic
    Commented Aug 3, 2017 at 11:10
-1

You can set & get cookie using php basic function like this:

//set cookie
$cookie_name = "magento";
$cookie_value = "How to Cookie";
setcookie($cookie_name, $cookie_value, time()+3600); /* expire in 1 hour */

//get cookie
if(!isset($_COOKIE[$cookie_name])) {
    echo "Cookie named '" . $cookie_name . "' is not set!";
} else {
    echo "Cookie '" . $cookie_name . "' is set!<br>";
    echo "Value is: " . $_COOKIE[$cookie_name];
}

Your Answer

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

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