Executing background processes from PHP on Windows
A summary of methods to launch Windows background processes from PHP.
On *nix, launching background processes is as simple as appending an ampersand (&) to the command. In Windows, it is not so simple to do from PHP.
If you use the PHP exec or shell_exec commands to run a process, PHP will wait for the process to quit before continuing.
This assumes that you are using PHP-CLI (from the command-line). Running PHP on a web server requires correct setup of configuration and permissions, such as safe_mode, safe_mode_exec_dir, etc.
For example, suppose one wanted to launch cmd from PHP, and then continue executing. The following examples do not work.
exec("cmd"); exec("cmd >NUL"); exec("cmd /c cmd"); exec("start /b cmd"); exec("runas cmd");
In each case, PHP waits for cmd to quit before continuing.
There are several workarounds mentioned in the comments of the PHP documentation of exec. Here is a summary of those methods, by order of preference.
- Start background process using the WScript.Shell object
- You can start the process using the Run method of the WScript.Shell object, which is built-in to Windows. By varying the second parameter, you can make the window hidden, visible, minimized, etc. By setting the third parameter to false, Run does not wait for the process to finish executing. This code only works on Windows.
$WshShell = new COM("WScript.Shell"); $oExec = $WshShell->Run("cmd /C dir /S %windir%", 0, false);
- Start background process using popen and pclose
- This code should work on Linux and Windows.
pclose(popen("start \"bla\" \"" . $exe . "\" " . escapeshellarg($args), "r"));
- Start background process with psexec
- This method requires installing the freeware pstools from sysinternals:
exec("psexec -d blah.bat");
- Start process without a window
- This is not really for background processes, but worth mentioning. Use the windows start command with /B switch to hide the window.
exec('start /B "window_name" "path to your exe"',$output,$return);
Disclaimer: This content is provided as-is. The information may be incorrect.