PHP: how to execute a command in background

How to execute a command in the background without PHP waiting for it to finish, on both Windows and Unix/Linux.

On Unix/Linux, we know that to run a command in the background we must use add > /dev/null & or > /dev/null 2>&1 & follow the command (We can see in this tutorial:

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

On Windows, you can run a command in the background by method:

$WshShell = new COM("WScript.Shell"); 
$oExec = $WshShell->Run("notepad.exe", 0, false); 
    echo 'done!';
    echo 'fail!';

Other method on Windows:


function runInBackground($path,$arguments) {
    $WshShell = new COM("WScript.Shell");
    $oShellLink = $WshShell->CreateShortcut("temp.lnk");
    $oShellLink->TargetPath = $path;
    $oShellLink->Arguments = $arguments;
    $oShellLink->WorkingDirectory = dirname($path);
    $oShellLink->WindowStyle = 1;
    $oExec = $WshShell->Run("temp.lnk", 0, false);
    return $oExec==0?true:false;


Other method on Windows:

pclose(popen('powershell.exe "Start-Process notepad.exe -WindowStyle Hidden"','r'));

Readmore about Start-Process:

How to track this process with PHP, how to check this process is finished, read next tutorial.

Leave a Reply