AktifPerunding

  • Home
  • About
  • Our Team
  • Portfolio
  • News
  • Contact

categories

  • Civil & Structure
  • Electrical
  • Electronic
  • Information & Technology
  • Mechanical
  • Photovoltaic
  • PHP
  • Programming
  • Solar Power
  • Technology

Execute Command Without Waiting For It To Finish

This article is about tips and tricks on executing command from PHP script without waiting it to finish

Admin APSB 11/04/2019 Information & Technology, PHP

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");

becomes:

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 backgroundExec($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 :

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

Use it as you wish.

AktifPerunding

DISCLAIMER: We are not responsible for any lost or corrupt personal data information when using this website

information

CONSULT . DESIGN . BUILD

Tel: +603 8959 3901

Email: [email protected]

Working Hours: 9AM-5PM (+8 GMT)

Instagram

© Copyright Aktif Perunding Sdn. Bhd. All Rights Reserved

Powered by Maximum Builders