How to set, get and unset session variable in Magento
How to set, get and unset session variable in Magento

What is session and How to set, get, unset session variable in Magento


In this article, we will learn how to set, get and unset session variable in Magento. Before doing so we will first try to understand what session is?

“The item you added to your cart a few days ago is still there. Where do you think it comes from? It is coming from the session.”

The session helps us in storing certain data and retrieve it.

Magento provides multiple options for storing session data like

  1. Filesystem Session storage
  2. Database Session storage
  3. Memcached Session storage
  4. Tmpfs-backed Filesystem Session storage

But we will get into it in detail later.

Magento Session is generally handled by “core/session” module.

READ MORE: How to learn coding online- 10 Apps to learn code

How to set session

Default structure

Mage::getSingleton(‘core/session’)->set<MySessionName>(<MySessionNameValue>);

Here MySessionName is the name of the session variable and MySessionNameValue is its value. Let understand it by an example

Let MySessionName = ‘MyName’;

and $MySessionNameValue = ‘Tesla’;

then

Mage::getSingleton(‘core/session’)->setMyName($MySessionNameValue);

This will store “Tesla” in the MyName session variable.

How to get session value

To get value from a session variable we use “get<MySessionName>()”.

Default structure

Mage::getSingleton(‘core/session’)->get<MySessionName>();

For example

$session_value = Mage::getSingleton(‘core/session’)->getMyName();

This will give the value of session variable and in this case “Tesla” in $session_value.

How to unset session variable

To unset session variable we use “uns<MySessionName>()”.

Default structure

Mage::getSingleton(‘core/session’)->uns<MySessionName>();

For example

Mage::getSingleton(‘core/session’)->unsMyName();

This will delete session MyName.

You can also use the following session in frontend

  1. Mage::getSingleton(‘customer/session’)
  2. Mage::getSingleton(‘core/session’)
  3. Mage::getSingleton(‘checkout/session’)

You can use the following session in backend

  1. Mage::getSingleton(‘adminhtml/session’)

READ MORE: 6 Reasons Why Magento Is The Best eCommerce Platform

If you liked this article, then do share with others. For the latest tech news follow techcresendo on TwitterFacebook, and LinkedIn

LEAVE A REPLY

Please enter your comment!
Please enter your name here