Execute command line functions in PHP

posted in: Linux, PHP | 0

Execute command line functions in PHP is really helpful.

exec('here you put what you would have typed on the command line')
chdir('here you put what you would have typed on the command line')

Below is an example of:

  • changing directories with chdir(‘[directory]’) and chdir(‘../’)
  • as well as executing a php phar package with exec(‘php ./doctrine-migrations.phar migrations:migrate –no-interaction’);
        if ($migration)
        {
            $bobDbMigrationFile = new DBMigrationBuilder($className, $propertiesKeysValues);

            // before you can run any migration - you need to drop the table that that migration affects
            $tableToRemove = strtolower($className);

            $db = new PDO('mysql:host=localhost;dbname=restdb', 'root', '');
            $dropTable = $db->prepare("DROP TABLE IF EXISTS $tableToRemove");
            $dropTable->execute();

            $dbtest = new PDO('mysql:host=localhost;dbname=resttestdb', 'root', '');
            $dropTestTable = $dbtest->prepare("DROP TABLE IF EXISTS $tableToRemove");
            $dropTestTable->execute();

            chdir(__DIR__ .'/../db/restdb/');
            exec('php ./doctrine-migrations.phar migrations:migrate --no-interaction');

            chdir('../');
            chdir('resttestdb');
            exec('php ./doctrine-migrations.phar migrations:migrate --no-interaction');

        }

Leave a Reply