How To Run Code From An External File/Script In Magento 2

In this article, I am going to show you a little trick for accessing Magento 2 core functionality from an external PHP file/script. The external file can be inside the Magento 2 root folder or subfolder. This will help you while developing a Magento 2 website.

Let us assume that in the below example, we have created a file called custom_script.php. Now we can run the file like www.example.com/custom_script.php in the browser.

Example file path: /var/www/html/magento_2/custom_script.php

To access the Magento 2 core functionality, we need to include the below code in the top of the external file,

use Magento\Framework\App\Bootstrap;
require __DIR__ . '/app/bootstrap.php';
$params = $_SERVER; 
$bootstrap = Bootstrap::create(BP, $params);

After including the above code, we can able to access the Magento 2 core functionality from the external file.

Here the example code to get customer information by customer id, product information by product id, and quote information by quote id from the external file,

<?php
use Magento\Framework\App\Bootstrap;
 
/**
 * If the external file is in the root folder
 */
require __DIR__ . '/app/bootstrap.php';

$params = $_SERVER;
 
$bootstrap = Bootstrap::create(BP, $params);
 
$obj = $bootstrap->getObjectManager();
 
$state = $obj->get('Magento\Framework\App\State');
$state->setAreaCode('frontend');

/**
 * Code to get the customer information by using customer id
 */
$customerId = 1;
$customer = $obj->get('\Magento\Customer\Model\CustomerFactory')
                ->create()
                ->load($customerId);

echo '<pre>';
    print_r($customer->getData());
echo '</pre>';

/**
 * Code to get the product information by using product id
 */ 
$productId = 1;
$product = $obj->get('Magento\Catalog\Model\ProductRepository')
               ->getById($productId);
 
echo '<pre>';
    print_r($product->getData());
echo '</pre>';

/**
 * Code to get the quote information by using quote id
 */
$quoteId = 1;
$quote = $obj->get('Magento\Checkout\Model\Session')
             ->getQuote()
             ->load($quoteId);
 
echo '<pre>';
    print_r($quote->getOrigData());
echo '</pre>';

Note:

  • If your external file is in the root folder call the bootstrap file as follows,

require __DIR__ . ‘/app/bootstrap.php’;

  • If your external file is not in the root folder, and it is in any other subfolder, call the bootstrap file using the full path as follows,

require  ‘/var/www/html/magento2/app/bootstrap.php’;

Here, /var/www/html/magento2 is the example file path. You can give your Magento 2 file path here.

Hope this helps.

One Comment on “How To Run Code From An External File/Script In Magento 2”

Leave a Reply

Your email address will not be published. Required fields are marked *