On Linux I can use shell_exec()
as below to run the command in background:
shell_exec("/usr/bin/nohup curl -o /dev/null --data \"$data\" $url >/dev/null 2>&1 &");
Note that the above line doesn't wait for the result and the code will resume instantly.
How can I achieve it on windows? It's preferable to be something built-in for windows.
I'd check out the Symfony Process component for this use case. It provides methods for executing synchronously and asynchronously. It can be easily installed through Composer, but it requires PHP 7.1 at least.
The documentation can be found here: https://symfony.com/doc/current/components/process.html
An example for your use case could look like this:
$process = new Process(['curl', '--data', $data, $url]);
$process->start();
Note that I omitted the -o
option because the output of the sub process won't show up unless you request it explicitly.
A quick browse yielded some posts that said that the start()
method blocks on Windows but it seems that a patch has already been implemented and merged: https://github.com/symfony/symfony/pull/10420
EDIT: If you don't want to use a library, you can use a combination of popen()
, pclose()
and the Windows tool start
:
pclose(popen('start /B curl --data "'.$data.'" '.$url, 'r'));
This runs the program in background without opening a window and immediately returns.
EDIT 2: Source for the trick with start /B
: http://php.net/manual/en/function.exec.php#86329