How to run a php script through the command line (and keep it running after logging out)

Vinayak picture Vinayak · Feb 22, 2009 · Viewed 21k times · Source

I am trying to run a php script on my remote Virtual Private Server through the command line. The process I follow is:

  1. Log into the server using PuTTY
  2. On the command line prompt, type> php myScript.php

The script runs just fine. BUT THE PROBLEM is that the script stops running as soon as I close the PuTTY console window.

I need the script to keep on running endlessly. How can I do that? I am running Debian on the server.

Thanks in advance.

Answer

Steve Weet picture Steve Weet · Feb 22, 2009

I believe that Ben has the correct answer, namely use the nohup command. nohup stands for nohangup and means that your program should ignore a hangup signal, generated when you're putty session is disconnected either by you logging out or because you have been timed out.

You need to be aware that the output of your command will be appended to a file in the current directory named nohup.out (or $HOME/nohup.out if permissions prevent you from creating nohup.out in the current directory). If your program generates a lot of output then this file can get very large, alternatively you can use shell redirection to redirect the output of the script to another file.

nohup php myscript.php >myscript.output 2>&1 &

This command will run your script and send all output (both standard and error) to the file myscript.output which will be created anew each time you run the program.

The final & causes the script to run in the background so you can do other things whilst it is running or logout.