PHP `exec` in the background but get STDOUT

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!


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.

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'){
    else {

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

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

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

Some more links:

Need Your Help

Dialog doesn't “pop up” but redirects the entire page

jquery dialog fullcalendar

I am currently working on a calendar using the Fullcalendar jquery plugin.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.