Working with Magento 2 its pretty usual, that you often needs to test or run any piece of code outside Magento. To do so, the following snippet will help you:
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 area code is 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.