What is Best Practice for running PHP in background?

8,510

There is no method specific to PHP when it comes to running jobs in the background. The widely accepted methods are:

  1. Using a screen. Install screen (if it is not already installed), then run your PHP script under a screen. You can detach from the screen anytime and log out of the machine and the script will continue running. Here is one of the few hundred tutorials available online about how to use screen.

  2. Using nohup. The usage is:

nohup <yourPHPcommand> &

The nohup will let your script 'say no' to the HANGUP signal when you log out, as a result, your PHP script will keep running even after you logout. The only problem is that you won't be able to bring that job/process to foreground and see the output(if it matters to you). You can redirect the output to a file and see what it is printing out from that file though.

Out of the above two, I recommend you use the screen. You can attach to the screen anytime you want and control the process the same way you would've if you had started in the foreground.

P.S:- Running the script with the ampersand (&) at the end does put it in the background, but the script/process gets killed when you log out of the terminal.

Share:
8,510

Related videos on Youtube

sfanjoy
Author by

sfanjoy

I like beer and I own a TI 99. The rest is self explanatory.

Updated on September 18, 2022

Comments

  • sfanjoy
    sfanjoy over 1 year

    When running the following on the command line it will be suspended until I issue the fg command:

    /usr/bin/php -r 'phpinfo();' &
    

    This is the case regardless if the PHP code is contained in a file with a shebang of #!/usr/bin/php.

    I am running CentOS and bash shell.

    • Celada
      Celada over 9 years
      Works for me. The & puts it in the background, it doesn't get "suspended".
  • sfanjoy
    sfanjoy over 9 years
    Thanks. I chose the nohup method because my scripts are batch style and are usually run from cron. All output is directed to a log file. On occasion the help desk will run them from the command line and will logout. The connection is sshd based and I have not observeed any process terminiation. Only the parent pid of the process changing to 1.