14

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

Thanks

23

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($duration)
            ->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.

  • @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. – MauroNigrele Feb 3 '16 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 Apr 12 '16 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 Jun 1 '16 at 8:17
  • @MauroNigrele function call in set and delete method should be createPublicCookieMetadata instead of createCookieMetadata – Shivam Jun 9 '16 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... – spiil Aug 3 '17 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, privacy policy and cookie policy

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