I want display the amount of items in the cart outside of magento. Thus I created this script inside a scripts folder in the magento directory:

require __DIR__ . '/../../app/bootstrap.php';
$bootstrap = \Magento\Framework\App\Bootstrap::create(BP, $_SERVER);
/** @var \Magento\Framework\App\Http $app */
$obj = $bootstrap->getObjectManager();

// Set the state (not sure if this is neccessary)
$state = $obj->get('Magento\Framework\App\State');

// Getting the object managers dependencies 
$quote = $obj->get('Magento\Checkout\Model\Session')->getQuote();
$helper = $obj->get('\Magento\Checkout\Helper\Cart');

echo json_encode(['items' => $helper->getItemsQty()]);

But for an unknown reason this suddenly just returns zero. I did not update the version so I think it might be some setting maybe?

How do I get the amount of items in the cart outside of magento?

PS: I know there are several answers already but I tried them all and they did not work either for different reasons like errors or so.


This seems to be some sort of Magento problem. After a night I called the page again and there is this strange behavior:

  • the cart amount on the magento page still shows a number and the popover shows my items although I did not setup persistent cart but I set the session time to a high value
  • if I go to the cart it is empty
  • the script still shows zero

Now if I clear my browser data and call magento and the script again both display zero (as there is nothing in the cart for real). If I then add items to the cart both display the correct value.

2 Answers 2


Who is requesting this script url?

If its not the customer (who has items in his/her cart), the bootstrap may be creating a new customer/visitor session, thus having an empty cart.

If you are the owner running this script, you must load the cart/quote by its id from the quote repository, before retrieving the cart contents.

On the other hand, if the customer him/herself is calling this script, make sure the script is sharing the same php session to identify the customer and retrieve his/her cart contents.

  • thanks for the answer, the customer is calling the script him/herself. but I found that it seems to be an magento problem. I updated my question.
    – steros
    Apr 12, 2017 at 11:19

I did not find the actual problem. But the problem is related to my local dev-environment with vagrant. After uploading it to my server I can't reproduce the error anymore.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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