Magento – how to add a product in cart from external php file in magento

cartmagento-1.7PHP

i've an external php file called addtocart.php who is located in my magento root folder. with this file i want to add a product to the cart. the product should have the following attributes:

sku name options price(!!) qty

EDIT: this is a screenshot of my magento folder structure: https://www.dropbox.com/s/vmli0973iflfski/Screenshot%202014-02-12%2009.44.39.png

this is my code: (only with qty and sku)

require_once('app/Mage.php');    
umask(0);
Mage::app('de');


$image = "uploads/52f7857f039b2.jpg";
// the ID of the product
$product_id  = 149;

$product     = Mage::getModel('catalog/product')->load($product_id);



$cart = Mage::getModel('checkout/cart');
$cart->init();
$params = array(
    'product' => $product_id,
    'qty' => 1,
    'options' => array(
        149 => array(
                'quote_path' => $image,
                'secret_key' => substr(md5(file_get_contents(Mage::getBaseDir() . $image)), 0, 20)),
    )
);

$cart->addProduct($product, $params);
$cart->save();


Mage::getSingleton('checkout/session')->setCartWasUpdated(true);

it does not work! can anybody tell me how to do this? Thank you! 🙂

Best Answer

The code looks pretty strait forward (and works locally with a sample configurable product). My guess is that you have a mal-formed $params array for those custom options.

It expects something along the lines of this...

$params = array(
    'product' => 1,
    'qty' => 1,
    'options' => array(
        26 => "value",
        42 => "another value here",
        71 => "yav"
)
);

What kind of custom option type is it that requires the value to be an array?

Related Topic