Search code examples
phpbackground-processasynchronous

Long running background process in PHP on windows machine


I have a script in PHP that uses Curl to hit a long list of URLs one by one and write the response to a file at the end, I want the list to be uploaded from a browser and do rest of the processing in background (without making the user to wait for response). I have already tried the following solutions -

    $command = "C:\wamp\bin\php\php5.5.12\php.exe ../background_process/subscribe_bg.php ".$file_temp_path;
    shell_exec(sprintf('%s > /dev/null 2>/dev/null &', $command));

This runs the script successfully, but makes the browser wait. (This will probably run in background on a Linux machine.)

    $command = "C:\wamp\bin\php\php5.5.12\php.exe ../background_process/subscribe_bg.php ".$file_temp_path;

    execInBackground($command);

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

I found this solution for windows machine, but doesn't work for me.The script does not execute at all.

Please suggest the best practice to run a long process(not very long ~30-40 Minutes) in background using PHP on a windows machine.


Solution

  • This Works perfectly for a windows machine, with all the output of the script written to the $response_file_path -

    $command = $PHP_DIR." ../background_process/subscribe_bg.php -p=".$file_path_arg." >../sublogs/responses/".$file_response_path." 2>../sublogs/error_logs/err.txt";
    
    execInBackground($command)
    
    function execInBackground($cmd) {
        if (substr(php_uname(), 0, 7) == "Windows"){
            pclose(popen("start /B ". $cmd, "r"));
            return 1;
        }
        else {
            return 0;
            //Or the code for linux machine.
        }
    }