Adjusting the Scope of your Magento Session
A long time ago I posted an article about extracting your Magento blocks outside of Magento. However many of you may have had an issue if you were combining a static/CMS website and Magento with your store sitting within a sub-folder.
Now what you might have noticed is that when your Magento session has started within say, http://www.mywebsite.com/shop/ and you try to echo a persistant cart in the header on your homepage (http://www.mywebsite.com) nothing shows up.
Well, the reason for this is that the Magento cookie path is incorrect. By default the cookie path is relevant to the Magento installation which means that if you use the following code to try to get your Magento session out on a lower (higher?) level of the website you’re going to run into problems.
require_once('shop/app/Mage.php'); $app = Mage::app(); // initialise our instance $app->loadArea(Mage_Core_Model_App_Area::AREA_FRONTEND); // why not eh? Mage::getSingleton('core/session', array('name'=>'frontend')); echo $app->getLayout()->getBlockSingleton('checkout/cart_sidebar')->setTemplate("checkout/cart/sidebar.phtml")->toHtml(); // echo our minicart thing
You see if you’re in a level outside of your installation – the browser is not going to use your Magento cookies – and therefore you cannot grab your session information. To combat this all you need to do is ensure that your cookie path is set to the root of your website by logging into your Magento admin and navigating to System>Configuration>Web>Session Cookie Management:
Just putting a “/” in the cookies path should do the job!
Thanks for visiting our blog – and have a great Christmas!