3

I have made a few external php scripts to update quantity and tracking numbers,etc Right now, i'm putting them in magento root and set the permission to 640. However, it's still accessible by the browser. I would like to make it accessible by cron and the owner/group only.

I tried to move the script to

magentoroot/script/

, and change the following in the script:

$file = fopen('../../qty.csv', 'r', '"');

require DIR . '../app/bootstrap.php';

$writer = new \Zend\Log\Writer\Stream(BP . '../var/log/import-update.log');

then the script stop working. what should i change in the file? script 1:

<?php $file = fopen('../qty.csv', 'r', '"'); // set path to the CSV file
if ($file !== false) {

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


    $state = $objectManager->get('Magento\Framework\App\State');
    $state->setAreaCode('adminhtml');

    // used for updating product info
    $productRepository = $objectManager->get('Magento\Catalog\Model\ProductRepository');

    // used for updating product stock
        $stockRegistry = $objectManager->get('Magento\CatalogInventory\Api\StockRegistryInterface');

        // add logging capability
        $writer = new \Zend\Log\Writer\Stream(BP . '/var/log/import-update.log');
        $logger = new \Zend\Log\Logger();
        $logger->addWriter($writer);
 // enter the number of data fields you require the product row inside the CSV file to contain
    $required_data_fields = 2;  //change for 3 to 2

    $header = fgetcsv($file); // get data headers and skip 1st row

    while ( $row = fgetcsv($file, 5000, ",") ) {

        $data_count = count($row);
        if ($data_count < 1) {
            continue;
        }

        $data = array();
        $data = array_combine($header, $row);

        $sku = $data['sku'];
        if ($data_count < $required_data_fields) {
            //$logger->info("Skipping product sku " . $sku . ". Not enough data to import.");
            continue;
        }

        $qty = trim($data['qty']);
        //$price = trim($data['price']);

       // echo 'Updating product SKU: '.$sku.', with Qty: '.$qty.PHP_EOL; // .' and Price:'.$price.'<br />';
        /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////updating price/////////////////////////////////////////////////////////////////////
        //try {
        //    $product = $productRepository->get($sku);
        //} 
        //catch (\Exception $e) {
        //    $logger->info("Invalid product SKU: ".$sku);
        //    continue;
        //}
        //
        // You can set other product data with $product->setAttributeName() if you want to update more data
        //if ($product->getPrice() != $price) {
        //    $product->setPrice($price) 
        //            ->setStoreId(0) // this is needed because if you have multiple store views, each individual store view will get "Use default value" unchecked for multiple attributes - which causes issues.
        //            ->save();
        //}
        /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////updating quantity/////////////////////////////////////////////////////////////////////
        try {
            //$stockItem = $stockRegistry->getStockItemBySku($sku);
            $stockItem = $stockRegistry->getStockItemBySku($sku);
        } 
        catch (\Exception $e) {
            //$logger->info("Invalid stock for product SKU: ".$sku);
            continue;
        }

        if ($stockItem->getQty() != $qty) {
            echo 'Updating SKU:'.$sku.', current qty:'.$stockItem->getQty().', updating to qty:'.$qty.PHP_EOL;
            $stockItem->setQty($qty);
            $stockItem->setIsInStock((int)($qty > 0));
            //if ($qty > 0) {
            //    $stockItem->setIsInStock(1);
            //}
            //if ($qty < 1) {
            //  $stockItem->setIsInStock(0); //clean up first time
            //}
            //$stockRegistry->updateStockItemBySku($sku, $stockItem);
    /*      $stockItem->setStockData(
                array(
                'use_config_manage_stock' => 0, 
                // checkbox for 'Use config settings' 
                'manage_stock' => 1, // manage stock
                //'min_sale_qty' => 1, // Shopping Cart Minimum Qty Allowed 
                'is_in_stock' => (int)($qty > 0), // Stock Availability of product
                'qty' => $qty // qty of product
                )
            );*/

            $stockRegistry->updateStockItemBySku($sku, $stockItem);
            $stockItem->save();
        }
    }
    fclose($file);
}

script 2:

<?php
$file = fopen('../track.csv', 'r', '"'); // set path to the CSV file
if ($file !== false)
{
    require __DIR__ . '/app/bootstrap.php';
    $bootstrap = \Magento\Framework\App\Bootstrap::create(BP, $_SERVER);
    $objectManager = $bootstrap->getObjectManager();
    $state = $objectManager->get('Magento\Framework\App\State');
    $state->setAreaCode('adminhtml');
    // add logging capability
    $writer = new \Zend\Log\Writer\Stream(BP . '/var/log/import-update.log');
    $logger = new \Zend\Log\Logger();
    $logger->addWriter($writer);


    class ShipmentObject{
    ...
    ...
    }

    /**
    * @param \Magento\Sales\Model\Order\Shipment\TrackFactory $shipmentTrackFactory
    * @param \Magento\Sales\Model\Order\ShipmentFactory $shipmentFactory
    * @param \Magento\Framework\DB\TransactionFactory $transactionFactory
    * @param \Magento\Sales\Api\OrderRepositoryInterface $orderRepository
    */
    $shipmentTrackFactory = $objectManager->get('\Magento\Sales\Model\Order\Shipment\TrackFactory');
    $shipmentFactory = $objectManager->get('\Magento\Sales\Model\Order\ShipmentFactory');
    $transactionFactory = $objectManager->get('\Magento\Framework\DB\TransactionFactory');
    $orderRepository = $objectManager->get('\Magento\Sales\Api\OrderRepositoryInterface');
    $orderFactory = $objectManager->get('\Magento\Sales\Model\OrderFactory');
    $invoiceService = $objectManager->get('Magento\Sales\Model\Service\InvoiceService');

    //create new class object
    $test = new ShipmentObject($shipmentTrackFactory,$shipmentFactory,$transactionFactory,$orderRepository,$orderFactory,$invoiceService);
    $test->setFile($file);
    $test->execute();
    //rewind($file);
    //ftruncate($file, 0); // empty the file once done
    file_put_contents('../track.csv',""); //empty the csv file
    fclose($file); 
5
  • why do you need them to be standalone scripts? Just put your code in a regular class that you can use via cron
    – Marius
    Commented Apr 19, 2019 at 5:29
  • can you show me an example how to do it? Commented Apr 19, 2019 at 16:14
  • i updated with my complete scripts in the question, please advise. For example, the script 1 i'm not sure how to put them in a regular class. for script 2, i do have a class called shipmentobject, but i'm not sure how to put everything else into the class(i need to create a shipment class object?) Commented Apr 19, 2019 at 16:38
  • find any answer????
    – Ali Raza
    Commented Oct 9, 2020 at 7:11
  • instead of moving the scripts into a sub-folder in magento folder. i put the scripts above the magento root directory, and change the require to like the following "require DIR . 'magento_root/app/bootstrap.php'; Commented Oct 11, 2020 at 20:54

1 Answer 1

1

This is not at all best practise. But you can use the below script to understand how this works.

<?php
use Magento\Framework\App\Bootstrap;

require __DIR__ . '/app/bootstrap.php';

$params = $_SERVER;

$bootstrap = Bootstrap::create(BP, $params);

//Call Object manager
$obj = $bootstrap->getObjectManager();

$state = $obj->get('Magento\Framework\App\State');
$state->setAreaCode('frontend');

$productId = 1;
$product = $obj->get('Magento\Catalog\Model\ProductRepository')
    ->getById($productId);

print "Product Name : \n";
print $product->getData('name');
print "\nProduct Price : \n";
print $product->getData('price');
?>

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.