1

I'm trying to execute a command (in both Windows and Linux) via PHP. My target is to have multiple instances of the command running at the same time (hence background) but I need to grab the output of each also.

This doesn't work as the output cannot be grabbed.

function execInBackground($cmd) { 
    if (substr(php_uname(), 0, 7) == "Windows"){ 
        pclose(popen("start /B ". $cmd, "r"));  
    } 
    else { 
        exec($cmd . " > /dev/null &");   
    } 
}

Will forking help me? I saw PHP exec in background using & is not working too but again where to get the output?

Any ideas would be great!

EDIT: We are using PHP v5.2, other PHP versions cannot be used!

Community
  • 1
  • 1
Birla
  • 1,170
  • 11
  • 30

3 Answers3

2

To be compatible with both Linux & Windows environments, you could use Symfony2 Process component. It will allow you to run code background while grabbing the output easily:

use Symfony\Component\Process\Process;

$process = new Process($cmd);
$process->start(function ($type, $buffer) {
    if ('err' === $type) {
        // Do something with error $buffer
    } else {
        // Do something with normal $input
    }
});

// Do something else

// Wait until the process completes
$process->wait();

Note that you should use $process->start() instead of $process->run() to allow background execution.

Some more links:

Community
  • 1
  • 1
Ville Mattila
  • 1,343
  • 3
  • 15
  • 28
  • This component looks great, but unfortunately we are running PHP5.2 so I cannot use this. I will try to get an old branch from the git repo. Thanks! – Birla Jan 23 '13 at 08:39
  • Important: `$process->wait();` is **mandatory**. Without it, the process *will be killed* immediately after your PHP application server is done sending a response. In other words, this "background" process will only run as long as its parent is alive. – mae Jun 21 '17 at 04:35
1

Exec the command with & and output to a file:

exec($cmd . " > output".$NumberOfInstance.".txt &"); 

After that you can read contents when its done.

exec($cmd . " > output".$NumberOfInstance.".txt ; php phpscriptwhereyouchecktheoutputfilewithaverylongname.php&"); 

Try this for executing a PHP script AFTER the first command was ended, using the ; between instructions.

1

you'll easy to have the output if using "Windows PowerShell" or run>cmd to execute your command .it'll be return results immediately, it not good solution if you want to get the output to handling, it just use to testing results

another case to execute command in window and linux:

if (getenv('OS')=='Windows_NT'){
        exec($pathToFileExecute.$command);
    }
    else {
        exec($command);
    }

$pathToFileExcute is no need on linux
ex: $pathToFileExecute = 'E:^\Setup^\wamp^\bin^\mysql^\mysql5.5.20^\bin^\';

Rain
  • 601
  • 6
  • 10