I want to run a custom PHP script in Magento 2 webshop using a custom module.
But I want it to run only when installing or during installation of my custom module.
To be specific, during setup:upgrade command and will trigger only once except if there's a change in my custom module version. 
Anyone tried that before?
Can you point me into right direction on how to do it? 
Thanks!
2 Answers 2
You can use PHP shell_exec() command for your requirement.
You can execute shell_exec() command in Install or Upgrade Schema of module. So when your module is installed or you change module version your code will be executed.
If it is not standalone PHP script then another approach would be to Just execute your Module's functions in Install script.
Find below example to execute shell script
<?php
namespace Vendor\Module\Setup;
use Magento\Framework\Setup\UpgradeSchemaInterface;
use Magento\Framework\Setup\ModuleContextInterface;
use Magento\Framework\Setup\SchemaSetupInterface;
class UpgradeSchema implements UpgradeSchemaInterface {
 /**
 * {@inheritdoc}
 */
 public function upgrade(
 SchemaSetupInterface $setup, ModuleContextInterface $context
 ) {
 if(version_compare($version1, $version2)){
 //execute your script here
 shell_exec('base_path/scriptname.php'); // this will execute custom php script at given location
 }
 }
}
- 
 can you site an example , I mean a sample code on implementationfmsthird– fmsthird2019年02月14日 07:25:55 +00:00Commented Feb 14, 2019 at 7:25
- 
 @magefms example includedMufaddal– Mufaddal2019年02月14日 07:32:27 +00:00Commented Feb 14, 2019 at 7:32
- 
 let me check. I'll update you laterfmsthird– fmsthird2019年02月14日 07:38:11 +00:00Commented Feb 14, 2019 at 7:38
- 
 is base_path dynamic or static? should i change it ?fmsthird– fmsthird2019年02月14日 08:00:08 +00:00Commented Feb 14, 2019 at 8:00
- 
 
I am not sure what you want exactly but according to your description, You may use magento default InstallSchema feature to achieve this.
Like if you create a module, and create following file.
File: [Vendor]/[Module]/Setup/InstallSchema.php
<?php
namespace [Vendor]\[Module]\Setup;
use Magento\Framework\Setup\InstallSchemaInterface;
use Magento\Framework\Setup\SchemaSetupInterface;
use Magento\Framework\Setup\ModuleContextInterface;
class InstallSchema implements InstallSchemaInterface
{
 public function install(SchemaSetupInterface $setup, ModuleContextInterface $context)
 {
 $setup->startSetup();
 // Your php script code here
 $setup->endSetup();
 }
}
You may execute your code in between, which will only be executed while only installation of your module.
- 
 
- 
 You want to execute php file through shell scripting ?Yash Shah– Yash Shah2019年02月14日 08:56:56 +00:00Commented Feb 14, 2019 at 8:56