php execute a background process


I need to execute a directory copy upon a user action, but the directories are quite large, so I would like to be able to perform such an action without the user being aware of the time it takes for the copy to complete.

Any suggestions would be much appreciated.

This question is tagged with php

~ Asked on 2008-09-05 14:43:48

19 Answers


Assuming this is running on a Linux machine, I've always handled it like this:

exec(sprintf("%s > %s 2>&1 & echo $! >> %s", $cmd, $outputfile, $pidfile));

This launches the command $cmd, redirects the command output to $outputfile, and writes the process id to $pidfile.

That lets you easily monitor what the process is doing and if it's still running.

function isRunning($pid){
        $result = shell_exec(sprintf("ps %d", $pid));
        if( count(preg_split("/\n/", $result)) > 2){
            return true;
    }catch(Exception $e){}

    return false;

~ Answered on 2008-09-05 14:49:53


Write the process as a server-side script in whatever language (php/bash/perl/etc) is handy and then call it from the process control functions in your php script.

The function probably detects if standard io is used as the output stream and if it is then that will set the return value..if not then it ends

proc_close( proc_open( "./command --foo=1 &", array(), $foo ) );

I tested this quickly from the command line using "sleep 25s" as the command and it worked like a charm.

(Answer found here)

~ Answered on 2008-09-05 15:13:54


You might want to try to append this to your command

>/dev/null 2>/dev/null &


shell_exec('service named reload >/dev/null 2>/dev/null &');

~ Answered on 2012-08-14 14:42:31


I'd just like to add a very simple example for testing this functionality on Windows:

Create the following two files and save them to a web directory:




echo "<pre>loading page</pre>";

function run_background_process()
    file_put_contents("testprocesses.php","foreground start time = " . time() . "\n");
    echo "<pre>  foreground start time = " . time() . "</pre>";

    // output from the command must be redirected to a file or another output stream 

    exec("php background.php > testoutput.php 2>&1 & echo $!", $output);

    echo "<pre>  foreground end time = " . time() . "</pre>";
    file_put_contents("testprocesses.php","foreground end time = " . time() . "\n", FILE_APPEND);
    return $output;

echo "<pre>calling run_background_process</pre>";

$output = run_background_process();

echo "<pre>output = "; print_r($output); echo "</pre>";
echo "<pre>end of page</pre>";


file_put_contents("testprocesses.php","background start time = " . time() . "\n", FILE_APPEND);
file_put_contents("testprocesses.php","background end time = " . time() . "\n", FILE_APPEND);

Give IUSR permission to write to the directory in which you created the above files

Give IUSR permission to READ and EXECUTE C:\Windows\System32\cmd.exe

Hit foreground.php from a web browser

The following should be rendered to the browser w/the current timestamps and local resource # in the output array:

loading page
calling run_background_process
  foreground start time = 1266003600
  foreground end time = 1266003600
output = Array
    [0] => 15010
end of page

You should see testoutput.php in the same directory as the above files were saved, and it should be empty

You should see testprocesses.php in the same directory as the above files were saved, and it should contain the following text w/the current timestamps:

foreground start time = 1266003600
foreground end time = 1266003600
background start time = 1266003600
background end time = 1266003610

~ Answered on 2010-02-12 20:40:50


If you need to just do something in background without the PHP page waiting for it to complete, you could use another (background) PHP script that is "invoked" with wget command. This background PHP script will be executed with privileges, of course, as any other PHP script on your system.

Here is an example on Windows using wget from gnuwin32 packages.

The background code (file test-proc-bg.php) as an exmple ...

sleep(5);   // some delay
file_put_contents('test.txt', date('Y-m-d/H:i:s.u')); // writes time in a file

The foreground script, the one invoking ...

$proc_command = "wget.exe http://localhost/test-proc-bg.php -q -O - -b";
$proc = popen($proc_command, "r");

You must use the popen/pclose for this to work properly.

The wget options:

-q    keeps wget quiet.
-O -  outputs to stdout.
-b    works on background

~ Answered on 2011-01-28 20:23:26


Here is a function to launch a background process in PHP. Finally created one that actually works on Windows too, after a lot of reading and testing different approaches and parameters.

function LaunchBackgroundProcess($command){
  // Run command Asynchroniously (in a separate thread)
  if(PHP_OS=='WINNT' || PHP_OS=='WIN32' || PHP_OS=='Windows'){
    // Windows
    $command = 'start "" '. $command;
  } else {
    // Linux/UNIX
    $command = $command .' /dev/null &';
  $handle = popen($command, 'r');
    return true;
  } else {
    return false;

Note 1: On windows, do not use /B parameter as suggested elsewhere. It forces process to run the same console window as start command itself, resulting in the process being processed synchronously. To run the process in a separate thread (asynchronously), do not use /B.

Note 2: The empty double quotes after start "" are required if the command is a quoted path. start command interprets the first quoted parameter as window title.

~ Answered on 2016-01-05 13:31:19


Well i found a bit faster and easier version to use

shell_exec('screen -dmS $name_of_screen $command'); 

and it works.

~ Answered on 2014-06-03 21:34:18


Can you arrange to fork off a separate process, and then run your copy in the background? It's been a while since I did any PHP, but the function pcntl-fork looks promising.

~ Answered on 2008-09-05 14:49:09


Use this function to run your program in background. It cross-platform and fully customizable.

function startBackgroundProcess(
    $stdin = null,
    $redirectStdout = null,
    $redirectStderr = null,
    $cwd = null,
    $env = null,
    $other_options = null
) {
    $descriptorspec = array(
        1 => is_string($redirectStdout) ? array('file', $redirectStdout, 'w') : array('pipe', 'w'),
        2 => is_string($redirectStderr) ? array('file', $redirectStderr, 'w') : array('pipe', 'w'),
    if (is_string($stdin)) {
        $descriptorspec[0] = array('pipe', 'r');
    $proc = proc_open($command, $descriptorspec, $pipes, $cwd, $env, $other_options);
    if (!is_resource($proc)) {
        throw new \Exception("Failed to start background process by command: $command");
    if (is_string($stdin)) {
        fwrite($pipes[0], $stdin);
    if (!is_string($redirectStdout)) {
    if (!is_string($redirectStderr)) {
    return $proc;

Note that after command started, by default this function closes the stdin and stdout of running process. You can redirect process output into some file via $redirectStdout and $redirectStderr arguments.

Note for windows users:
You cannot redirect stdout/stderr to nul in the following manner:

startBackgroundProcess('ping', null, 'nul', 'nul');

However, you can do this:

startBackgroundProcess('ping >nul 2>&1');

Notes for *nix users:

1) Use exec shell command if you want get actual PID:

$proc = startBackgroundProcess('exec ping -c 15', null, '/dev/null', '/dev/null');

2) Use $stdin argument if you want to pass some data to the input of your program:

startBackgroundProcess('cat > input.txt', "Hello world!\n");

~ Answered on 2016-07-04 08:06:25


You might try a queuing system like Resque. You then can generate a job, that processes the information and quite fast return with the "processing" image. With this approach you won't know when it is finished though.

This solution is intended for larger scale applications, where you don't want your front machines to do the heavy lifting, so they can process user requests. Therefore it might or might not work with physical data like files and folders, but for processing more complicated logic or other asynchronous tasks (ie new registrations mails) it is nice to have and very scalable.

~ Answered on 2013-02-14 23:57:33


A working solution for both Windows and Linux. Find more on My github page.

function run_process($cmd,$outputFile = '/dev/null', $append = false){
                if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {//'This is a server using Windows!';
                        $cmd = 'wmic process call create "'.$cmd.'" | find "ProcessId"';
                        $handle = popen("start /B ". $cmd, "r");
                        $read = fread($handle, 200); //Read the output 
                        $pid=substr($pid,0,strpos($pid,';') );
                        $pid = (int)$pid;
                        pclose($handle); //Close
                    $pid = (int)shell_exec(sprintf('%s %s %s 2>&1 & echo $!', $cmd, ($append) ? '>>' : '>', $outputFile));
                    return $pid;
            function is_process_running($pid){
                if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {//'This is a server using Windows!';
                        //tasklist /FI "PID eq 6480"
                    $result = shell_exec('tasklist /FI "PID eq '.$pid.'"' );
                    if (count(preg_split("/\n/", $result)) > 0 && !preg_match('/No tasks/', $result)) {
                        return true;
                    $result = shell_exec(sprintf('ps %d 2>&1', $pid));
                    if (count(preg_split("/\n/", $result)) > 2 && !preg_match('/ERROR: Process ID out of range/', $result)) {
                        return true;
                return false;
            function stop_process($pid){
                    if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {//'This is a server using Windows!';
                            $result = shell_exec('taskkill /PID '.$pid );
                        if (count(preg_split("/\n/", $result)) > 0 && !preg_match('/No tasks/', $result)) {
                            return true;
                            $result = shell_exec(sprintf('kill %d 2>&1', $pid));
                        if (!preg_match('/No such process/', $result)) {
                            return true;

~ Answered on 2017-10-07 05:50:08


Thanks to this answer: A perfect tool to run a background process would be Symfony Process Component, which is based on proc_* functions, but it's much easier to use. See its documentation for more information.

~ Answered on 2019-01-28 20:32:18


Instead of initiating a background process, what about creating a trigger file and having a scheduler like cron or autosys periodically execute a script that looks for and acts on the trigger files? The triggers could contain instructions or even raw commands (better yet, just make it a shell script).

~ Answered on 2012-04-26 11:22:37


If you are looking to execute a background process via PHP, pipe the command's output to /dev/null and add & to the end of the command.

exec("bg_process > /dev/null &");

Note that you can not utilize the $output parameter of exec() or else PHP will hang (probably until the process completes).

~ Answered on 2020-11-10 23:21:09


I am heavily using fast_cgi_finish_request()

In combination with a closure and register_shutdown_function()

$message ='job executed';
$backgroundJob = function() use ($message) {
     //do some work here
    echo $message;

Then register this closure to be executed before shutdown.


Finally when the response was sent to the client you can close the connection to the client and continue working with the PHP process:


The closure will be executed after fast_cgi_finish_request.

The $message will not be visible at any time. And you can register as much closures as you want, but take care about script execution time. This will only work if PHP is running as a Fast CGI module (was that right?!)

~ Answered on 2014-10-02 23:00:40


If using PHP there is a much easier way to do this using pcntl_fork:

~ Answered on 2014-07-02 15:40:07


For those of us using Windows, look at this:


I too wrestled with getting a program to run in the background in Windows while the script continues to execute. This method unlike the other solutions allows you to start any program minimized, maximized, or with no window at all. [email protected]'s solution does work but it sometimes produces an unwanted window on the desktop when you really want the task to run hidden.

start Notepad.exe minimized in the background:

$WshShell = new COM("WScript.Shell"); 
$oExec = $WshShell->Run("notepad.exe", 7, false); 

start a shell command invisible in the background:

$WshShell = new COM("WScript.Shell"); 
$oExec = $WshShell->Run("cmd /C dir /S %windir%", 0, false); 

start MSPaint maximized and wait for you to close it before continuing the script:

$WshShell = new COM("WScript.Shell"); 
$oExec = $WshShell->Run("mspaint.exe", 3, true); 

For more info on the Run() method go to:

Edited URL:

Go to instead as the link above no longer exists.

~ Answered on 2015-06-05 17:05:45


PHP scripting is not like other desktop application developing language. In desktop application languages we can set daemon threads to run a background process but in PHP a process is occuring when user request for a page. However It is possible to set a background job using server's cron job functionality which php script runs.

~ Answered on 2014-08-03 12:50:32


I know it is a 100 year old post, but anyway, thought it might be useful to someone. You can put an invisible image somewhere on the page pointing to the url that needs to run in the background, like this:

<img src="run-in-background.php" border="0" alt="" width="1" height="1" />

~ Answered on 2011-08-12 02:54:29

Most Viewed Questions: