Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 609
Vinayak Avatar asked Feb 22 '09 18:02

Vinayak


People also ask

How do I run a PHP script continuously?

You can put a task (such as command or script) in a background by appending a & at the end of the command line. The & operator puts command in the background and free up your terminal. The command which runs in background is called a job. You can type other command while background command is running.

How do I run a PHP script from the command line with arguments?

To pass command line arguments to the script, we simply put them right after the script name like so... Note that the 0th argument is the name of the PHP script that is run. The rest of the array are the values passed in on the command line. The values are accessed via the $argv array.

Can we use PHP in command line?

As of version 4.3. 0, PHP supports a new SAPI type (Server Application Programming Interface) named CLI which means Command Line Interface. As the name implies, this SAPI type main focus is on developing shell (or desktop as well) applications with PHP.


2 Answers

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.

like image 183
Steve Weet Avatar answered Oct 14 '22 05:10

Steve Weet


An easy way is to run it though nohup:

nohup php myScript.php & 
like image 40
Ben Avatar answered Oct 14 '22 07:10

Ben