<p>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.</p>

<p>Any suggestions would be much appreciated.</p>

[{'answer_id': 45962, 'author': 'Matt Sheppard', 'author_id': 797, 'author_profile': 'https://Stackoverflow.com/users/797', 'pm_score': 2, 'selected': False, 'text': '<p>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 <a href="http://au2.php.net/manual/en/function.pcntl-fork.php" rel="nofollow noreferrer">pcntl-fork</a> looks promising. </p>\n'}, {'answer_id': 45966, 'author': 'Mark Biek', 'author_id': 305, 'author_profile': 'https://Stackoverflow.com/users/305', 'pm_score': 10, 'selected': True, 'text': '<p>Assuming this is running on a Linux machine, I\'ve always handled it like this:</p>\n\n<pre><code>exec(sprintf("%s &gt; %s 2&gt;&amp;1 &amp; echo $! &gt;&gt; %s", $cmd, $outputfile, $pidfile));\n</code></pre>\n\n<p>This launches the command <code>$cmd</code>, redirects the command output to <code>$outputfile</code>, and writes the process id to <code>$pidfile</code>.</p>\n\n<p>That lets you easily monitor what the process is doing and if it\'s still running.</p>\n\n<pre><code>function isRunning($pid){\n    try{\n        $result = shell_exec(sprintf("ps %d", $pid));\n        if( count(preg_split("/\\n/", $result)) &gt; 2){\n            return true;\n        }\n    }catch(Exception $e){}\n\n    return false;\n}\n</code></pre>\n'}, {'answer_id': 46008, 'author': 'Eric Goodwin', 'author_id': 1430, 'author_profile': 'https://Stackoverflow.com/users/1430', 'pm_score': 5, 'selected': False, 'text': '<p>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.</p>\n\n<p>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 </p>\n\n<pre><code>proc_close( proc_open( "./command --foo=1 &amp;", array(), $foo ) );\n</code></pre>\n\n<p>I tested this quickly from the command line using "sleep 25s" as the command and it worked like a charm.</p>\n\n<p>(<a href="http://ca.php.net/manual/en/function.exec.php" rel="noreferrer">Answer found here</a>)</p>\n'}, {'answer_id': 2254982, 'author': 'Captain Obvious', 'author_id': 172166, 'author_profile': 'https://Stackoverflow.com/users/172166', 'pm_score': 4, 'selected': False, 'text': '<p>I\'d just like to add a very simple example for testing this functionality on Windows:</p>\n\n<p>Create the following two files and save them to a web directory:</p>\n\n<p>foreground.php:</p>\n\n<pre><code>&lt;?php\n\nini_set("display_errors",1);\nerror_reporting(E_ALL);\n\necho "&lt;pre&gt;loading page&lt;/pre&gt;";\n\nfunction run_background_process()\n{\n    file_put_contents("testprocesses.php","foreground start time = " . time() . "\\n");\n    echo "&lt;pre&gt;  foreground start time = " . time() . "&lt;/pre&gt;";\n\n    // output from the command must be redirected to a file or another output stream \n    // http://ca.php.net/manual/en/function.exec.php\n\n    exec("php background.php &gt; testoutput.php 2&gt;&amp;1 &amp; echo $!", $output);\n\n    echo "&lt;pre&gt;  foreground end time = " . time() . "&lt;/pre&gt;";\n    file_put_contents("testprocesses.php","foreground end time = " . time() . "\\n", FILE_APPEND);\n    return $output;\n}\n\necho "&lt;pre&gt;calling run_background_process&lt;/pre&gt;";\n\n$output = run_background_process();\n\necho "&lt;pre&gt;output = "; print_r($output); echo "&lt;/pre&gt;";\necho "&lt;pre&gt;end of page&lt;/pre&gt;";\n?&gt;\n</code></pre>\n\n<p>background.php:</p>\n\n<pre><code>&lt;?\nfile_put_contents("testprocesses.php","background start time = " . time() . "\\n", FILE_APPEND);\nsleep(10);\nfile_put_contents("testprocesses.php","background end time = " . time() . "\\n", FILE_APPEND);\n?&gt;\n</code></pre>\n\n<p>Give IUSR permission to write to the directory in which you created the above files</p>\n\n<p>Give IUSR permission to READ and EXECUTE C:\\Windows\\System32\\cmd.exe</p>\n\n<p>Hit foreground.php from a web browser</p>\n\n<p>The following should be rendered to the browser w/the current timestamps and local resource # in the output array:</p>\n\n<pre><code>loading page\ncalling run_background_process\n  foreground start time = 1266003600\n  foreground end time = 1266003600\noutput = Array\n(\n    [0] =&gt; 15010\n)\nend of page\n</code></pre>\n\n<p>You should see testoutput.php in the same directory as the above files were saved, and it should be empty</p>\n\n<p>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:</p>\n\n<pre><code>foreground start time = 1266003600\nforeground end time = 1266003600\nbackground start time = 1266003600\nbackground end time = 1266003610\n</code></pre>\n'}, {'answer_id': 4832703, 'author': 'Neven Boyanov', 'author_id': 594345, 'author_profile': 'https://Stackoverflow.com/users/594345', 'pm_score': 3, 'selected': False, 'text': '<p>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.</p>\n\n<p>Here is an example on Windows using wget from gnuwin32 packages.</p>\n\n<p>The background code (file test-proc-bg.php) as an exmple ...</p>\n\n<pre><code>sleep(5);   // some delay\nfile_put_contents(\'test.txt\', date(\'Y-m-d/H:i:s.u\')); // writes time in a file\n</code></pre>\n\n<p>The foreground script, the one invoking ...</p>\n\n<pre><code>$proc_command = "wget.exe http://localhost/test-proc-bg.php -q -O - -b";\n$proc = popen($proc_command, "r");\npclose($proc);\n</code></pre>\n\n<p>You must use the popen/pclose for this to work properly.</p>\n\n<p>The wget options:</p>\n\n<pre><code>-q    keeps wget quiet.\n-O -  outputs to stdout.\n-b    works on background\n</code></pre>\n'}, {'answer_id': 7035131, 'author': 'Alex', 'author_id': 891051, 'author_profile': 'https://Stackoverflow.com/users/891051', 'pm_score': -1, 'selected': False, 'text': '<p>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:</p>\n\n<p><code>&lt;img src="run-in-background.php" border="0" alt="" width="1" height="1" /&gt;</code></p>\n'}, {'answer_id': 10332392, 'author': 'Brian Warshaw', 'author_id': 1344, 'author_profile': 'https://Stackoverflow.com/users/1344', 'pm_score': 1, 'selected': False, 'text': '<p>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).</p>\n'}, {'answer_id': 11954827, 'author': 'wlf', 'author_id': 1595154, 'author_profile': 'https://Stackoverflow.com/users/1595154', 'pm_score': 5, 'selected': False, 'text': "<p>You might want to try to append this to your command</p>\n\n<pre><code>&gt;/dev/null 2&gt;/dev/null &amp;\n</code></pre>\n\n<p>eg.</p>\n\n<pre><code>shell_exec('service named reload &gt;/dev/null 2&gt;/dev/null &amp;');\n</code></pre>\n"}, {'answer_id': 14886239, 'author': 'scones', 'author_id': 2004683, 'author_profile': 'https://Stackoverflow.com/users/2004683', 'pm_score': 2, 'selected': False, 'text': '<p>You might try a queuing system like <a href="https://github.com/chrisboulton/php-resque" rel="nofollow">Resque</a>. 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.</p>\n\n<p>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.\nTherefore 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.</p>\n'}, {'answer_id': 24025322, 'author': 'Morfidon', 'author_id': 2393593, 'author_profile': 'https://Stackoverflow.com/users/2393593', 'pm_score': 3, 'selected': False, 'text': "<p>Well i found a bit faster and easier version to use</p>\n\n<pre><code>shell_exec('screen -dmS $name_of_screen $command'); \n</code></pre>\n\n<p>and it works.</p>\n"}, {'answer_id': 24535424, 'author': 'John Foley', 'author_id': 1775336, 'author_profile': 'https://Stackoverflow.com/users/1775336', 'pm_score': 1, 'selected': False, 'text': '<p>If using PHP there is a much easier way to do this using pcntl_fork:</p>\n\n<p><a href="http://www.php.net/manual/en/function.pcntl-fork.php" rel="nofollow">http://www.php.net/manual/en/function.pcntl-fork.php</a></p>\n'}, {'answer_id': 25104811, 'author': 'shihab mm', 'author_id': 3024401, 'author_profile': 'https://Stackoverflow.com/users/3024401', 'pm_score': 0, 'selected': False, 'text': "<p>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.</p>\n"}, {'answer_id': 26170949, 'author': 'sgotre', 'author_id': 2859620, 'author_profile': 'https://Stackoverflow.com/users/2859620', 'pm_score': 1, 'selected': False, 'text': "<p>I am heavily using <code>fast_cgi_finish_request()</code></p>\n\n<p>In combination with a closure and register_shutdown_function()</p>\n\n<pre><code>$message ='job executed';\n$backgroundJob = function() use ($message) {\n     //do some work here\n    echo $message;\n}\n</code></pre>\n\n<p>Then register this closure to be executed before shutdown. </p>\n\n<pre><code>register_shutdown_function($backgroundJob);\n</code></pre>\n\n<p>Finally when the response was sent to the client you can close the connection to the client and continue working with the PHP process:</p>\n\n<pre><code>fast_cgi_finish_request();\n</code></pre>\n\n<p>The closure will be executed after fast_cgi_finish_request. </p>\n\n<p>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. \nThis will only work if PHP is running as a Fast CGI module (was that right?!)</p>\n"}, {'answer_id': 30672118, 'author': 'Jimmy Ilenloa', 'author_id': 2259400, 'author_profile': 'https://Stackoverflow.com/users/2259400', 'pm_score': 0, 'selected': False, 'text': '<p>For those of us using <strong>Windows</strong>, look at this:</p>\n\n<p>Reference: <a href="http://php.net/manual/en/function.exec.php#43917" rel="nofollow noreferrer">http://php.net/manual/en/function.exec.php#43917</a></p>\n\n<blockquote>\n  <p>I too wrestled with getting a program to run in the background in\n  Windows while the script continues to execute.  This method unlike the\n  other solutions allows you to start any program minimized, maximized,\n  or with no window at all.  llbra@phpbrasil\'s solution does work but it\n  sometimes produces an unwanted window on the desktop when you really\n  want the task to run hidden.</p>\n</blockquote>\n\n<p>start Notepad.exe minimized in the background: </p>\n\n<pre><code>&lt;?php \n$WshShell = new COM("WScript.Shell"); \n$oExec = $WshShell-&gt;Run("notepad.exe", 7, false); \n?&gt; \n</code></pre>\n\n<p>start a shell command invisible in the background: </p>\n\n<pre><code>&lt;?php \n$WshShell = new COM("WScript.Shell"); \n$oExec = $WshShell-&gt;Run("cmd /C dir /S %windir%", 0, false); \n?&gt; \n</code></pre>\n\n<p>start MSPaint maximized and wait for you to close it before continuing the script: </p>\n\n<pre><code>&lt;?php \n$WshShell = new COM("WScript.Shell"); \n$oExec = $WshShell-&gt;Run("mspaint.exe", 3, true); \n?&gt; \n</code></pre>\n\n<p>For more info on the Run() method go to: \n<a href="http://msdn.microsoft.com/library/en-us/script56/html/wsMthRun.asp" rel="nofollow noreferrer">http://msdn.microsoft.com/library/en-us/script56/html/wsMthRun.asp</a></p>\n\n<p><strong>Edited URL:</strong></p>\n\n<p>Go to <a href="https://technet.microsoft.com/en-us/library/ee156605.aspx" rel="nofollow noreferrer">https://technet.microsoft.com/en-us/library/ee156605.aspx</a> instead as the link above no longer exists.</p>\n'}, {'answer_id': 34612967, 'author': 'Slava', 'author_id': 1709903, 'author_profile': 'https://Stackoverflow.com/users/1709903', 'pm_score': 3, 'selected': False, 'text': '<p>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.</p>\n\n<pre><code>function LaunchBackgroundProcess($command){\n  // Run command Asynchroniously (in a separate thread)\n  if(PHP_OS==\'WINNT\' || PHP_OS==\'WIN32\' || PHP_OS==\'Windows\'){\n    // Windows\n    $command = \'start "" \'. $command;\n  } else {\n    // Linux/UNIX\n    $command = $command .\' /dev/null &amp;\';\n  }\n  $handle = popen($command, \'r\');\n  if($handle!==false){\n    pclose($handle);\n    return true;\n  } else {\n    return false;\n  }\n}\n</code></pre>\n\n<p>Note 1: On windows, do not use <code>/B</code> parameter as suggested elsewhere. It forces process to run the same console window as <code>start</code> command itself, resulting in the process being processed synchronously. To run the process in a separate thread (asynchronously), do not use <code>/B</code>.</p>\n\n<p>Note 2: The empty double quotes after <code>start ""</code> are required if the command is a quoted path. <code>start</code> command interprets the first quoted parameter as window title.</p>\n'}, {'answer_id': 38179655, 'author': 'Pascal9x', 'author_id': 2782340, 'author_profile': 'https://Stackoverflow.com/users/2782340', 'pm_score': 2, 'selected': False, 'text': '<p>Use this function to run your program in background. It cross-platform and fully customizable.</p>\n\n<pre><code>&lt;?php\nfunction startBackgroundProcess(\n    $command,\n    $stdin = null,\n    $redirectStdout = null,\n    $redirectStderr = null,\n    $cwd = null,\n    $env = null,\n    $other_options = null\n) {\n    $descriptorspec = array(\n        1 =&gt; is_string($redirectStdout) ? array(\'file\', $redirectStdout, \'w\') : array(\'pipe\', \'w\'),\n        2 =&gt; is_string($redirectStderr) ? array(\'file\', $redirectStderr, \'w\') : array(\'pipe\', \'w\'),\n    );\n    if (is_string($stdin)) {\n        $descriptorspec[0] = array(\'pipe\', \'r\');\n    }\n    $proc = proc_open($command, $descriptorspec, $pipes, $cwd, $env, $other_options);\n    if (!is_resource($proc)) {\n        throw new \\Exception("Failed to start background process by command: $command");\n    }\n    if (is_string($stdin)) {\n        fwrite($pipes[0], $stdin);\n        fclose($pipes[0]);\n    }\n    if (!is_string($redirectStdout)) {\n        fclose($pipes[1]);\n    }\n    if (!is_string($redirectStderr)) {\n        fclose($pipes[2]);\n    }\n    return $proc;\n}\n</code></pre>\n\n<p>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.</p>\n\n<p><strong>Note for windows users:</strong><br>\nYou cannot redirect stdout/stderr to <code>nul</code> in the following manner:</p>\n\n<pre><code>startBackgroundProcess(\'ping yandex.com\', null, \'nul\', \'nul\');\n</code></pre>\n\n<p>However, you can do this:</p>\n\n<pre><code>startBackgroundProcess(\'ping yandex.com &gt;nul 2&gt;&amp;1\');\n</code></pre>\n\n<p><strong>Notes for *nix users:</strong></p>\n\n<p>1) Use exec shell command if you want get actual PID:</p>\n\n<pre><code>$proc = startBackgroundProcess(\'exec ping yandex.com -c 15\', null, \'/dev/null\', \'/dev/null\');\nprint_r(proc_get_status($proc));\n</code></pre>\n\n<p>2) Use $stdin argument if you want to pass some data to the input of your program:</p>\n\n<pre><code>startBackgroundProcess(\'cat &gt; input.txt\', "Hello world!\\n");\n</code></pre>\n'}, {'answer_id': 46617107, 'author': 'Joshy Francis', 'author_id': 6417678, 'author_profile': 'https://Stackoverflow.com/users/6417678', 'pm_score': 2, 'selected': False, 'text': '<p>A working solution for both Windows and Linux. Find more on <a href="https://github.com/JoshyFrancis/php_background_process" rel="nofollow noreferrer">My github page</a>.</p>\n\n<pre><code>function run_process($cmd,$outputFile = \'/dev/null\', $append = false){\n                    $pid=0;\n                if (strtoupper(substr(PHP_OS, 0, 3)) === \'WIN\') {//\'This is a server using Windows!\';\n                        $cmd = \'wmic process call create "\'.$cmd.\'" | find "ProcessId"\';\n                        $handle = popen("start /B ". $cmd, "r");\n                        $read = fread($handle, 200); //Read the output \n                        $pid=substr($read,strpos($read,\'=\')+1);\n                        $pid=substr($pid,0,strpos($pid,\';\') );\n                        $pid = (int)$pid;\n                        pclose($handle); //Close\n                }else{\n                    $pid = (int)shell_exec(sprintf(\'%s %s %s 2&gt;&amp;1 &amp; echo $!\', $cmd, ($append) ? \'&gt;&gt;\' : \'&gt;\', $outputFile));\n                }\n                    return $pid;\n            }\n            function is_process_running($pid){\n                if (strtoupper(substr(PHP_OS, 0, 3)) === \'WIN\') {//\'This is a server using Windows!\';\n                        //tasklist /FI "PID eq 6480"\n                    $result = shell_exec(\'tasklist /FI "PID eq \'.$pid.\'"\' );\n                    if (count(preg_split("/\\n/", $result)) &gt; 0 &amp;&amp; !preg_match(\'/No tasks/\', $result)) {\n                        return true;\n                    }\n                }else{\n                    $result = shell_exec(sprintf(\'ps %d 2&gt;&amp;1\', $pid));\n                    if (count(preg_split("/\\n/", $result)) &gt; 2 &amp;&amp; !preg_match(\'/ERROR: Process ID out of range/\', $result)) {\n                        return true;\n                    }\n                }\n                return false;\n            }\n            function stop_process($pid){\n                    if (strtoupper(substr(PHP_OS, 0, 3)) === \'WIN\') {//\'This is a server using Windows!\';\n                            $result = shell_exec(\'taskkill /PID \'.$pid );\n                        if (count(preg_split("/\\n/", $result)) &gt; 0 &amp;&amp; !preg_match(\'/No tasks/\', $result)) {\n                            return true;\n                        }\n                    }else{\n                            $result = shell_exec(sprintf(\'kill %d 2&gt;&amp;1\', $pid));\n                        if (!preg_match(\'/No such process/\', $result)) {\n                            return true;\n                        }\n                    }\n            }\n</code></pre>\n'}, {'answer_id': 54409868, 'author': 'MAChitgarha', 'author_id': 4215651, 'author_profile': 'https://Stackoverflow.com/users/4215651', 'pm_score': 2, 'selected': False, 'text': '<p>Thanks to <a href="https://stackoverflow.com/a/46677126/4215651">this answer</a>: A perfect tool to run a background process would be <a href="https://github.com/symfony/process" rel="nofollow noreferrer">Symfony Process Component</a>, which is based on <code>proc_*</code> functions, but it\'s much easier to use. See <a href="https://symfony.com/doc/current/components/process.html" rel="nofollow noreferrer">its documentation</a> for more information.</p>\n'}, {'answer_id': 64778230, 'author': 'TheKarateKid', 'author_id': 1692693, 'author_profile': 'https://Stackoverflow.com/users/1692693', 'pm_score': 1, 'selected': False, 'text': "<p>If you are looking to execute a background process via PHP, pipe the command's output to <code>/dev/null</code> and add <code>&amp;</code> to the end of the command.</p>\n<pre><code>exec(&quot;bg_process &gt; /dev/null &amp;&quot;);\n</code></pre>\n<p>Note that you can <strong>not</strong> utilize the <code>$output</code> parameter of <code>exec()</code> or else PHP will hang (probably until the process completes).</p>\n"}, {'answer_id': 71655444, 'author': 'Justin Jack', 'author_id': 1678210, 'author_profile': 'https://Stackoverflow.com/users/1678210', 'pm_score': 0, 'selected': False, 'text': '<p>New answer to an old question.  Using <a href="https://github.com/justincjack/phpthreads" rel="nofollow noreferrer">this library</a>, the following code would spawn an asynchronous/parallel PHPThread to do background work.</p>\n<ul>\n<li>Must have pcntl, posix, and socket extensions</li>\n<li>Designed for/tested in CLI mode.</li>\n</ul>\n<p>EZ code sample:</p>\n<pre><code> function threadproc($thread, $param) {\n \n    echo &quot;\\tI\'m a PHPThread.  In this example, I was given only one parameter: \\&quot;&quot;. print_r($param, true) .&quot;\\&quot; to work with, but I can accept as many as you\'d like!\\n&quot;;\n \n    for ($i = 0; $i &lt; 10; $i++) {\n        usleep(1000000);\n        echo &quot;\\tPHPThread working, very busy...\\n&quot;;\n    }\n \n    return &quot;I\'m a return value!&quot;;\n}\n \n\n$thread_id = phpthread_create($thread, array(), &quot;threadproc&quot;, null, array(&quot;123456&quot;));\n \necho &quot;I\'m the main thread doing very important work!\\n&quot;;\n \nfor ($n = 0; $n &lt; 5; $n++) {\n    usleep(1000000);\n    echo &quot;Main thread...working!\\n&quot;;\n}\n \necho &quot;\\nMain thread done working.  Waiting on our PHPThread...\\n&quot;;\n \nphpthread_join($thread_id, $retval);\n \necho &quot;\\n\\nOur PHPThread returned: &quot; . print_r($retval, true) . &quot;!\\n&quot;;\n</code></pre>\n'}, {'answer_id': 73118719, 'author': 'Dev Matee', 'author_id': 3743412, 'author_profile': 'https://Stackoverflow.com/users/3743412', 'pm_score': 0, 'selected': False, 'text': '<h2>From PHP official documentation(php.net)</h2>\n<pre><code>&lt;?php\nfunction execInBackground($cmd) {\n    if (substr(php_uname(), 0, 7) == &quot;Windows&quot;){\n        pclose(popen(&quot;start /B &quot;. $cmd, &quot;r&quot;)); \n    }\n    else {\n        exec($cmd . &quot; &gt; /dev/null &amp;&quot;);  \n    }\n}\n?&gt;\n</code></pre>\n'}]
['https://Stackoverflow.com/questions/45953', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1071/']