Set, get and delete data from cookie in magento 2

Set, get and delete data from cookie in magento 2

In this article we learn how to Set, get and delete data from cookie in Magento2.

So first, Create a folder “Cookie” under app/code/Namespace/Module/ and create a file “Custom.php” under app/code/Namespace/Module/Cookie/.

Here is the code snippet that will be written in file app/code/Namespace/Module/Cookie/Custom.php . In the following code I have get, set and delete data from remote address.:

<?php
namespace Namespace\Module\Cookie;

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

class Custom
{
    /**
     * @var \Magento\Framework\Stdlib\CookieManagerInterface
     */
    protected $_cookieManager;

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

    /**
     * @var \Magento\Framework\Session\SessionManagerInterface
     */
    protected $_sessionManager;

    /**
     * @var \Magento\Framework\ObjectManagerInterface
     */
    protected $_objectManager;

    /**
     * @var Magento\Framework\HTTP\PhpEnvironment\RemoteAddress
     */
    protected $_remoteAddressInstance;

    /**
     * [__construct ]
     *
     * @param CookieManagerInterface                    $cookieManager
     * @param CookieMetadataFactory                     $cookieMetadataFactory
     * @param SessionManagerInterface                   $sessionManager
     * @param \Magento\Framework\ObjectManagerInterface $objectManager
     */
    public function __construct(
        CookieManagerInterface $cookieManager,
        CookieMetadataFactory $cookieMetadataFactory,
        SessionManagerInterface $sessionManager,
        \Magento\Framework\ObjectManagerInterface $objectManager
    ) {
        $this->_cookieManager = $cookieManager;
        $this->_cookieMetadataFactory = $cookieMetadataFactory;
        $this->_sessionManager = $sessionManager;
        $this->_objectManager = $objectManager;
        $this->_remoteAddressInstance = $this->_objectManager->get(
            'Magento\Framework\HTTP\PhpEnvironment\RemoteAddress'
        );
    }

    /**
     * Get data from cookie set in remote address
     *
     * @return value
     */
    public function get()
    {
        return $this->_cookieManager->getCookie($this->getRemoteAddress());
    }

    /**
     * Set data to cookie in remote address
     *
     * @param [string] $value    [value of cookie]
     * @param integer  $duration [duration for cookie]
     *
     * @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(
            $this->getRemoteAddress(),
            $value,
            $metadata
        );
    }

    /**
     * delete cookie remote address
     *
     * @return void
     */
    public function delete()
    {
        $this->_cookieManager->deleteCookie(
            $this->getRemoteAddress(),
            $this->_cookieMetadataFactory
                ->createCookieMetadata()
                ->setPath($this->_sessionManager->getCookiePath())
                ->setDomain($this->_sessionManager->getCookieDomain())
        );
    }

    /**
     * used to get remote address, in which cookie data is set
     *
     * @return [string] [returns remote address]
     */
    public function getRemoteAddress()
    {
        return $this->_remoteAddressInstance->getRemoteAddress();
    }
}

In the above code, I have created a function get() that is used to get data stored in cookie.
And there is another function set(), which is used to set data in cookie with time duration, i.e. cookie unset its value after that given time duration. The function accepts two parameters:
First parameter is $value => this contains the value which you want to set in cookie, and second parameter is $duration => contains the time duration/limit (in seconds) for cookie.

Now about the function delete(), as it name says delete, means the function deletes/removes/unsets the cookie.

Now we proceed to another part, i.e. how to and from where we set, get and delete cookie. To get, set and delete cookie you can use the following code snippet :

$objectManager = \Magento\Core\Model\ObjectManager::getInstance();

/*-------begin-code to set data to cookie----------*/
$objectManager->get(
   'Namespace\Module\Cookie\Custom'
)->set("custom_data", 3600);
// here it calls the function set() from Namespace/Module/Cookie/Custom.php file. In this "custom_data" is a string value that is set in cookie with the name of remote address and "3600" are seconds upto which "custom_data" value is set in cookie. After 3600 the value of remote address from cookie will be unset.

/*-------end-code to set data to cookie----------*/

/*-------begin-code to get data from cookie----------*/
$value = $objectManager->get(
   'Namespace\Module\Cookie\Custom'
)->get();
echo $value;
// here it calls the function get() from Namespace/Module/Cookie/Custom.php file. $value contains the value that was set to cookie. In this example it contains "custom_data" .

/*-------end-code to get data from cookie----------*/

/*-------begin-code to delete cookie----------*/
$objectManager->get(
   'Namespace\Module\Cookie\Custom' 
)->delete();
// here it calls the function delete() from Namespace/Module/Cookie/Custom.php file and the cookie will be deleted/unset.

/*-------end-code to delete cookie----------*/

That’s all in this article, hope it will help you, try the above code and
if you have any issue just comment below.

. . .

Comments (2)

Add Your Comment

  • Franzim Barruk
    How can I access the session data outside of magento, like if magento is in /shop and I need to access it in /forum on the same web root?
  • Rafael Corrêa Gomes ♛
    Thanks for sharing!
  • css.php