How to unset session in Magento?

user1443655 picture user1443655 · Jun 8, 2012 · Viewed 33k times · Source

I am using session in my magento custom module.Below is my code

$session = Mage::getSingleton("core/session", array("name"=>"frontend"));

$session->setData("day_filter", 'weeks');
$session->setData("days", '5');          
$session->setData("next_delivery_date", '2012-05-12');

The above code is working fine, but now i want to unset or destroy all the value? Can you please provide me the solution how to unset all set values?

Answer

Drew Hunter picture Drew Hunter · Jun 8, 2012

There are several ways to unset session variables in Magento. Most of these (not all) are defined in Varien_Object and so are avialable to all objects in Magento that extend it.

unsetData:

    $session->unsetData('day_filter');
    $session->unsetData('days');
    $session->unsetData('next_delivery_date');

uns (which will be marginally slower and ultimately executes unsetData anyway):

   $session->unsDayFilter();
   $session->unsDays();
   $session->unsNextDeliveryDate();

getData

Not a mistake! A relatively unkown method exists in Mage_Core_Model_Session_Abstract_Varien. The getData method in this class contains an optional boolean second parameter which if passed true will clear the variable while returning it.

So $session->getData('day_filter', true); would return the session variable day_filter and also clear it from the session at the same time.

Set to null:

   $session->setData('day_filter', NULL);
   $session->setData('days', NULL);
   $session->setData('next_delivery_date', NULL);

unsetAll | clear

Finally you could use the nuclear option (BEWARE: This will unset ALL DATA in the session, not just the data you have added):

$session->unsetAll(); or $session->clear(); (both aliases of each other)