How to manage Cookies in Magento 2

A cookie is a small piece of data sent from a website and stored on the user’s computer by the user’s web browser while the user is browsing. Then, whenever he is back, he can easily get those data. It’s really convenient, isn’t it? In this blog, I would like to introduce you a detailed guide about how to manage cookies in Magento 2.

how to manage cookie in magento 2

Step 1: Setting up Module

In order to manage cookies in Magento 2, we need to create a module. Let’s name it: CookieDemo.

In your Magento root, create the following folders:
_  app/code/Magenest
_  app/code/Magenest/CookieDemo
_  app/code/Magenest/CookieDemo/etc

In the etc folder of the module, create a file called module.xml with the following content:

Next, register the module by creating registration.php file in the app/code/Magenest/CookieDemo/ folder with the following content:

Then, in the etc/frontend folder of the module, create a file called routes.xml:

The preparation is done, now let’s move on Step 2.

Step 2: Manage Cookies in Magento 2 by Controller

Firstly, In your Magento root, create the following folder: app/code/Magenest/CookieDemo/Controller

Now we will create controllers base on what we want to do with cookies:

  • If you want to save your cookies, in the Controller folder, create an action file called SetCookie.php contains:

  • To get Cookie data, create GetCookie.php with the below content:

  • Apply this snippet to the DeleteCookie.php in order to delete:

 

Well done, you just completed this module. Let’s open your browser and go to the following Url to check the result:
http://localhost/[MAGENTO_ROOT]/cookie/cookie/[actions_you_want_to_do]

Hope you find this article helpful and have fun learning Magento.

 

 

 

 

Share

Comments (4)

  1. Add custom link in header in Magento 2 | Run your e-commerce store with ease!
    […] Before we begin, if you don’t know how to create a simple custom module in Magento 2, please follow the Step 1 in our guide here : http://magenest.com/manage-cookie-magento-2/ […]

Speak Your Mind

83 + = 86