Cookie Management – Set and Get Cookie in Same Function

cookie

I'm trying to set a cookie and immediately get it in a function:

Mage::getSingleton('core/cookie')->set('productLanded', $product_sku, 86400, '/');
$this->product_landed = Mage::getSingleton('core/cookie')->get('productLanded');

I'm not able to print on a page the value of $this->product_landed as soon I call the function, I always need a page refresh. Any clue?

Best Answer

When you set method, it is just preparing the request headers to ask the browser to set the cookie in it and in order to get the cookie retrieved through php, you need to wait for another request send after saving the cookie on browser.

Here you can try something below:

Either use $_COOKIE immediately after setting the cookie value,

OR

if (the condition to set cookie) {
   Mage::getSingleton('core/cookie')->set('productLanded', $product_sku, 86400, '/');
   Mage::register('productLanded', true);
}

//Where you trying to get the value:
$productLanded = Mage::getSingleton('core/cookie')->get('productLanded');
if (!$productLanded) {
   $productLanded = Mage::registry('productLanded');
}