Magento Tutorials Run Magento 2 Code Externally

« Back to Magento Tutorials

If you're working with Magento 2 often you'll find sometimes you need to use Magento 2 code outside of the Magento platform. This can be easily achieved with the following lines of code.

/* */
use Magento\Framework\App\Bootstrap;

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

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

// Your Magento 2 code here

The above code sets the area code as the frontend, but you change 'frontend' to 'adminhtml' to run code as if you're in the Admin.

You have the Object Manager in $objectManager so you can retrieve any other objects that you require.

If the file is going to be placed in a different folder to the Magento 2 root folder, simply modify the path to app/bootstrap.php.