How to Set, Get and Unset Session Variables in Magento?

In this quick article, we will see how we can handle the session variable (set a new session variable, get the value of the existing session variable and deleting existing session variable) in Magento.

Magento has the following four session models,

  • Core: Used to store global session data which you can use throughout the website (i.e, cookies, IP address, error messages). This can be accessed using Mage::getModel(‘core/session’) object.
  • Customer: Used to store customer related session data (i.e, logging in or out, name, id, email, the customer’s group). This can be accessed using Mage::getModel(‘customer/session’) object.
  • Checkout: Used to store checkout related session data (i.e, cart totals, items, checkout progress). This can be accessed using Mage::getModel(‘checkout/session’) object.
  • Admin: Used to store admin related session data which you can use anywhere in the admin areas. This can be accessed using Mage::getModel(‘admin/session’) object.

Set Session Variable:

Look at the following syntax and example to set the session variable in Magento.

Syntax:

Mage::getSingleton('core/session')->set<YOUR SESSION NAME>(<SESSION VALUE>);

(Or)

Mage::getSingleton('core/session')->setData(<YOUR SESSION NAME>, <SESSION VALUE>);

Example:

Mage::getSingleton('core/session')->setMyName('John');

(Or)

Mage::getSingleton('core/session')->setData('MyName', 'John');

Here, “MyName” is a session variable.

Get Session Variable:

Look at the following syntax and example to get the session variable in Magento.

Syntax:

Mage::getSingleton('core/session')->get<YOUR SESSION NAME>();

(Or)

Mage::getSingleton('core/session')->getData(<YOUR SESSION NAME>);

Example:

$getSessionName = Mage::getSingleton('core/session')->getMyName();

(Or)

$getSessionName = Mage::getSingleton('core/session')->getData('MyName');

Unset Session Variable:

Look at the following syntax and example to unset the session variable in Magento.

Syntax:

Mage::getSingleton('core/session')->uns<YOUR SESSION NAME>();

Example:

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

Note: The MyName can be any text you want but set, get and uns prefixes are required.

Hope this helps.

Leave a Reply

Your email address will not be published. Required fields are marked *