Magento 2: Run code in external file/script
This article shows how to run Magento 2 code in an external file/script. The external file can be inside the Magento root folder or outside of it.
This example considers that the file is present in the Magento 2 root folder. Let us name the file as abc.php. So, we want to execute some code when we open http://example.com/abc.php.
Here is the code to be written in the external file.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 | <?php use Magento\Framework\App\Bootstrap; /** * If your external file is in root folder */ require __DIR__ . '/app/bootstrap.php'; /** * If your external file is NOT in root folder * Let's suppose, your file is inside a folder named 'xyz' * * And, let's suppose, your root directory path is * /var/www/html/magento2 */ // $rootDirectoryPath = '/var/www/html/magento2'; // require $rootDirectoryPath . '/app/bootstrap.php'; $params = $_SERVER; $bootstrap = Bootstrap::create(BP, $params); $obj = $bootstrap->getObjectManager(); $state = $obj->get('Magento\Framework\App\State'); $state->setAreaCode('frontend'); $quoteId = 1; $quote = $obj->get('Magento\Checkout\Model\Session') ->getQuote() ->load($quoteId); echo '<pre>'; print_r($quote->getOrigData()); echo '</pre>'; $productId = 1; $product = $obj->get('Magento\Catalog\Model\ProductRepository') ->getById($productId); echo '<pre>'; print_r($product->getData()); echo '</pre>'; ?> |
A good discussion is going on here regarding this topic.
Hope this helps. Thanks.





Mukesh Chapagain is a graduate of Kathmandu University (Dhulikhel, Nepal) from where he holds a Masters degree in Computer Engineering. Mukesh is a passionate web developer who has keen interest in open source technologies, programming & blogging.