Magento 1 Cart Session – How to Empty Cart or Clear Session Externally

cartmagento-1session

I have a unique workflow for redeeming vouchers on our site through Magento. I have a form that users use for inputting a series of vouchers to get products. It isn't "in" Magento as a CMS page or anything of that nature. The code I am using to achieve access to Magento's resources/models is as followed:

<?php

require_once('../app/Mage.php'); //Path to Magento
umask(0);
Mage::app();

// Now you can run ANY Magento code you want

/**
* Get the resource model
*/
$resource = Mage::getSingleton('core/resource');

I have several codes that can be used to clear session or cart contents but for whatever reason, I can't get them to work by just calling on Mage.php. Here are my codes:

Version 1:

// Empty shopping cart
Mage::getSingleton('checkout/cart')->truncate();

Version 2:

// Clear session data
Mage::getSingleton('checkout/session')->clear();

Version 3:

$quote = Mage::getSingleton('checkout/session')->getQuote();
$quote->delete();

None of these will work with the method I listed above. I am placing it after the "$resource…" line. Is there a better way to do this?

The Goal: Everytime a user visits this "voucher form", which is the landing page – I want their shopping cart to be emptied. Thanks.

Best Answer

This one should work as it removes all items from the current quote:

Mage::getSingleton('checkout/cart')->truncate();

But you need to save it afterwards:

Mage::getSingleton('checkout/cart')->save();

By the way, you can remove the following line:

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

since you don't use the variable and instantiating this singleton doesn't do anything in particular.