2

We need to show recently viewed product by customer based on browser and i try to below code.

    $cookie = Mage::getSingleton('core/cookie');

    if ($cookie->get('recent_product')) { 
        $recent_product = $cookie->get('recent_product'); 
        $Current_prd = explode(",",$cookie->get('recent_product'));

        if (!in_array($productId, $Current_prd)) {
            $recent_product=$recent_product.",".$productId;   
        }
        # $cookie->get('recent_product');
        $cookie->set('recent_product', $recent_product ,time()+86400,'/');
    } else { 
        $recent_product =array();
        $recent_product=$productId;
        $cookie = Mage::getSingleton('core/cookie');
        $cookie->set('recent_product',$recent_product ,time()+86400,'/');
    }

It is set the cookie. But when i close the browser, not able to get the previous cookie value.

What i missing the above code?.

3

Finally I get the solution. Just removed the time() key.

$cookie = Mage::getSingleton('core/cookie');

if ($cookie->get('recent_product')) { 
    $recent_product = $cookie->get('recent_product'); 
    $Current_prd = explode(",",$cookie->get('recent_product'));

    if (!in_array($productId, $Current_prd)) {
        $recent_product=$recent_product.",".$productId;   
    }
    # $cookie->get('recent_product');
    $cookie->set('recent_product', $recent_product ,86400,'/');
} else { 
    $recent_product =array();
    $recent_product=$productId;
    $cookie = Mage::getSingleton('core/cookie');
    $cookie->set('recent_product',$recent_product ,86400,'/');
}
0

Your code works in principle; something is off with your display logic:

<?php
ini_set('display_errors',true);
error_reporting(E_ALL | E_STRICT);
require 'app/Mage.php';
Mage::setIsDeveloperMode(true);
umask(0);
Mage::app();

/* @var $cookie Mage_Core_Model_Cookie */
$cookie = Mage::getSingleton('core/cookie');

if ($cookie->get('recent_product')) {
    var_dump($cookie->get('recent_product'));
}
else {
    $cookie = Mage::getSingleton('core/cookie');
    $cookie->set('recent_product','foo' ,time()+86400,'/');
}

Looking further, shouldn't your else use implode() based on how you are processing it in the if?

} else { 
    $recent_product = array();
    $recent_product = $productId;
    $cookie = Mage::getSingleton('core/cookie');
    $cookie->set('recent_product',implode(',',$recent_product) ,time()+86400,'/');
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.