Execute Command Without Waiting For It To Finish


Read {count} times since 2020

If you just execute a terminal command using exec or system in PHP, the page will only load completely until the command has been finished. If you are running commands to run a websocket server, the page will not load, because the start server command won’t terminate. So to avoid this problem you should just do a simple trick, Just add > /dev/null & after the command you’re running.
Here is a quick example :

exec("php -q server.php");


exec("php -q server.php  > /dev/null &");

Or you can wrap it all in a function to run the commands in both Windows and Linux :

function <span style="color: red;">bgExec</span>($cmd) {
 if(substr(php_uname(), 0, 7) == "Windows"){
  pclose(popen("start /B ". $cmd, "r")); 
 }else {
  exec($cmd . " > /dev/null &"); 

So, by the function you can call the command like this :

bgExec("php -q server.php");

Use it as you wish.

Show Comments