📜 ⬆️ ⬇️

Running background processes from PHP to Windows

In * nix, running background processes is accomplished simply by adding an ampersand (&) to the command. On Windows, it is not so easy to make PHP.

If you use system call functions in PHP, like exec, system, passthru, or shell_exec, then these methods will cause the program to hang, waiting for the called process to finish.

The methods described below assume that you are using PHP-CLI (working with php from the command line). Running PHP on a web server requires proper configuration and permissions, such as safe_mode, safe_mode_exec_dir, etc.
')
For example, we want to call cmd from PHP, but so that the program continues to perform actions.
The examples below 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 close.

There are several workarounds mentioned in the comments to the PHP documentation for the exec () function

A summary of these methods, in order of preference:

Start process using popen and pclose

This code should work on Linux and Windows.
$ exe = "cmd.exe";
pclose (popen ('start "bla" "'. $ exe. '"'. escapeshellarg ($ args), 'r'));

Start a background process using a WScript.Shell object

This code only works on Windows.
$ WshShell = new COM ("WScript.Shell");
// Run cmd minimized
$ oExec = $ WshShell-> Run ("cmd", 7, false);
// Run cmd in the background, the icon on the taskbar is not displayed
$ oExec = $ WshShell-> Run ("cmd / C dir / S% windir%", 0, false);

Read more about the Run () method in msdn.

Start the background process using the PsExec utility
This method requires the installation of the free PsTools utility from Sysinternals
exec ("psexec -d cmd.exe");

The author of this text root {Dog} imcms.ru can send him an invite.

Source: https://habr.com/ru/post/70810/


All Articles