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: http://tutorialspots.com/linux-how-to-download-multiple-files-in-background-4217.html

<?php 
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); 
if($oExec==0){
    echo 'done!';
}else{
    echo 'fail!';
}

Other method on Windows:

<?php

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;
    $oShellLink->Save();
    $oExec = $WshShell->Run("temp.lnk", 0, false);
    unset($WshShell,$oShellLink,$oExec);
    @unlink("temp.lnk");
    return $oExec==0?true:false;
}

runInBackground("notepad.exe","");

Other method on Windows:

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

Readmore about Start-Process: https://docs.microsoft.com/en-us/powershell/module/Microsoft.PowerShell.Management/Start-Process?view=powershell-6

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

Leave a Reply