Use cmd commands in scripts made to run in shell - cakephp 3.0

0

I was wondering if you have how to use native windows CMD commands, from scripts made to run in the cakephp shell.

I already run tasks that run in cmd, but with the commands of the framework itself but would like to use other commands.

    
asked by anonymous 31.05.2016 / 22:22

1 answer

0

I do not really understand the doubt, I suppose you want to create a shell in cakephp, such as:

namespace App\Shell;

use Cake\Console\Shell;

class HelloShell extends Shell
{
    public function main()
    {
        $this->out('Hello world.');
    }
}

But let him execute commands that exist on the machine.

  

Understand that commands running in CMD are mostly global executables.

To run Windows command you will obviously need to be on a Windows server and will not necessarily need cakephp, but only php, in case we have 3 functions:

  • exec - returns the program response in an array type reference ( second parameter)

  • system - returns the response directly in the output, or if it is HTTP already prints as if using echo , you can also get the last line of the output and the return response of the application (usually it's a number)

  • shell_exec - Performs a shell command and returns the result a string

  

It's important to note that if you're going to use arguments in your commands you'll need to use escapeshellarg or escapeshellcmd

namespace App\Shell;

use Cake\Console\Shell;

class HelloShell extends Shell
{
    public function main()
    {
        $resposta = shell_exec('dir');

        $this->out($resposta);
    }

    public function raiz()
    {
        $resposta = shell_exec('dir \');

        $this->out($resposta);
    }

    public function foo($pasta)
    {
        $resposta = shell_exec('dir ' . $pasta);

        $this->out($resposta);
    }
}

After saving the file, you should be able to execute the following commands:

  • Displays the contents of the current folder, usually the one that called the main script o varying from the larger application's address (for example apache):

    bin/cake hello
    
  • Displays the contents of the root folder:

    bin/cake hello raiz
    
  • Displays the contents of a folder that you determine:

    bin/cake hello foo /a/b/c
    

They will show something like:

O volume na unidade C não tem nome.
O Número de Série do Volume é AEE4-3225

Pasta de C:\Users\Guilherme\Exemplo

18/08/2016  23:06    <DIR>          .
18/08/2016  23:06    <DIR>          ..
14/07/2016  23:14    <DIR>          pasta
28/04/2016  21:03                21 .bash_history
               1 arquivo(s)          21 bytes
              3 pasta(s)   267.064.922.112 bytes disponíveis
    
24.08.2016 / 07:10