Running Magento 2.3.1.

I'm having trouble understanding how to get the customer's checkout/cart session data from an external PHP script.

The script is hosted and run on the same domain as the Magento store, and it's located in Magento's root directory. I'm running it from the same browser. All caches are disabled.

I have 3 items in my Magento cart, but when I run the script, it does not find any items:


$bootstrap = \Magento\Framework\App\Bootstrap::create(BP, $_SERVER);
$obj = $bootstrap->getObjectManager();

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

// Get cart items
$quote      = $obj->get('Magento\Checkout\Model\Session')->getQuote();
$quoteItems = $quote->getAllVisibleItems();

echo "Found " . count($quoteItems) . " cart items";

// Expected output:
// Found 3 cart items

// Actual output:
// Found 0 cart items

P.S. Please do not comment that ObjectManager should not be used directly. It is not helpful, and this is for a one-off script on an internal development environment only.

  • Your code is correct and giving correct cart items!
    – Pawan
    May 23, 2019 at 18:04
  • @Pawan Wow, that's strange. Are you running only this code from [magento_root]/somescript.php file?
    – WackGet
    May 23, 2019 at 18:33
  • Yes, exactely...
    – Pawan
    May 23, 2019 at 18:40
  • What about if you log in as customer on another tab? I'm wondering whether its session related. May 23, 2019 at 20:03
  • @DominicXigen Still nothing. I bet it is session related, because when I try to get any type of session (Customer, Checkout, Catalog) the session objects are empty. But I'm not sure why, if the code is correct and caches are disabled.
    – WackGet
    May 23, 2019 at 20:42

1 Answer 1


Looks like this was caused by missing settings under

Stores > Configuration > General > Web > Default Cookie Settings.

The Cookie Path and Cookie Domain fields were blank. I entered / and www.example.com respectively, saved, cleared configuration/page caches, deleted all my cookies, then tried my script again, and it was able to find my cart items.

The above code works OK. Thanks to the commenters for their help.

For anyone else experiencing session/cookie issues in Magento 2, remember that several things can influence sessions:

  • Session and cookie settings in Magento as described above
  • HTTP vs HTTPS - make sure you're not mixing request types
  • Server-side caching including PHP opcache, Memcached, Redis etc.
  • Client-side caching including web browser settings (check cookies in the browser itself and look for inconsistent cookie paths, names, etc.)
  • P.S. ObjectManager rules.
    – WackGet
    May 24, 2019 at 1:17

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.