Run Magento 2 Command On Root Directory With PHP Script

Magento 2 command With php script

Follow below instructions to run the magento 2 commands:

  1. Create a new file on Magento 2 root directory(command.php).
  2. Add the following codes in the newly created file.
<?php
use Magento\Framework\App\Bootstrap;
require 'app/bootstrap.php';
$bootstrap = Bootstrap::create(BP, $_SERVER);
$objectManager = $bootstrap->getObjectManager();
$state = $objectManager->get('Magento\Framework\App\State');
$state->setAreaCode('frontend');
//command code here
/*shell_exec('your_magento_2_commands');
             --OR--
system('your_magento_2_commands');  
*/
/* system('php bin/magento setup:upgrade');
system('php bin/magento setup:static-content:deploy -f');
system('php bin/magento indexer:reindex');
system('php bin/magento cache:flush');
system('php bin/magento cache:clean');
echo "Your Commands have been run successfully.";
*/
/*--OR--*/
shell_exec('php bin/magento setup:upgrade');
shell_exec('php bin/magento setup:static-content:deploy -f');
shell_exec('php bin/magento indexer:reindex');
shell_exec('php bin/magento cache:flush');
shell_exec('php bin/magento cache:clean');
echo "Your Commands have been run successfully.";
   //file ends here
?>

3. Now run this newly created file on the browser with following url: your_base_url/command.php (new file)

4. Now your commands have been run successfully as screenshot shown here.