Php – Magento customer/session not working


This problem first came into awareness as the order histories page (*/sales/order/history/) in frontend was displaying nothing but a short message: You have placed no orders.

After some debugging, it turns out the problem lies with this function:


It does not return a session entity containing current customer's information except the website id, which is why the order collection returns an empty result after filtering on the customer id.

There is actually a post on Stack Overflow discussing a similar problem:
Customer session is different in different parts of a Magento website
. But it has not given a good explaination.

And what is confusing is that, with my case, the function works well in some parts but not the others. For example, I inserted

<?php echo var_export(Mage::getSingleton('customer/session')->getCustomerId(), true) ?>  

into the catalog product list template, and it displays the customer id after login. But the same line returns Null in the order histories page.

I located these codes in app/code/core/Mage/Customer/Model/Session.php

public function getCustomer()
    $customer = Mage::getModel('customer/customer')
    if ($this->getId()) {
    return $this->_customer;

After setting the website id, it loads the customer entity depending on $this->getId().

Why the 'id' attribute of customer session entity is not always valid? Can someone share his knowledge please. Many thanks.

Best Solution

I'd be careful with Magento when assuming that the problem lies with one particular area. You can head down a pretty deep rabbit hole before realising you need to start all over.

If you're accurate in that the problem lies with the session getter, try this:

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

But I would also keep looking at other options. Sounds similar to the problems a lot of people have with caching. Consider trying the same with all caching switched off. The full page cache can do unexpected things to variable values.

What file are you echoing from in your example? I'd need to know this before helping any further.

Related Question