Sometimes you need to run Magento 2 code externally, in the following cases:

  • Magento 2 integration with other frameworks or platforms that are installed on the same web server,
  • quick test execution of some method, for example, cron job.

For example, create a test.php file in the Magento 2 root directory and add the following code to it:


ini_set('display_errors', 1);

use Magento\Framework\App\Bootstrap;
require __DIR__ . '/app/bootstrap.php';
$bootstrap = Bootstrap::create(BP, $_SERVER);
$obj = $bootstrap->getObjectManager();
$state = $obj->get(Magento\Framework\App\State::class);
$object = $obj->create(\VendorName\ModuleName\Folder\Class::class);

VendorName\ModuleName\Folder\Class - the name of the class, you want to execute;
someMethod - the name of the method you want to execute;
Attention! Make sure the __DIR__. '/app/bootstrap.php is the correct path to the Magento 2 app/bootstrap.php file.

You can run the test.php in the web-browser or from the CLI:

php test.php