Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Running PHP script from command line as background process

I'm trying to run a PHP script continually in the background via the command line in Linux. I have tried the command php filename.php & but it seems like the script execution terminates very quickly, while it should keep running until the process is terminated.

Any suggestions?

like image 372
Kyle Avatar asked Aug 08 '11 22:08

Kyle


People also ask

Can I run PHP script from command line?

You just follow the steps to run PHP program using command line. Open terminal or command line window. Goto the specified folder or directory where php files are present.

How do I run a script in the background process?

Running shell command or script in background using nohup command. Another way you can run a command in the background is using the nohup command. The nohup command, short for no hang up, is a command that keeps a process running even after exiting the shell.

How do I know if PHP script is running in background?

If you started it in background use ps aux | grep time. php to get PID. Then just kill PID . If process started in foreground, use to interrupt it.

How do I run a PHP script continuously?

The best way to achieve OP's goal is to use one cron job to poll a script every 1, 5, or however many minutes. That script should check a file (or db value) for a date + time. If the date + time is ≤ the current time, it should look through the full queue of tasks and do any that are ready.


2 Answers

Are you sure the script doesn't contain any errors? This is what normally makes "execution terminates very quickly".
First, append:

error_reporting(E_ALL); ini_set('display_errors', 1);

at the top of your script to display any errors it may have, then you can use:

nohup php filename.php &

nohup runs a command even if the session is disconnected or the user logs out.

OR

nohup php filename.php >/dev/null 2>&1 &

Same as above but doesn't create nohup.out file.


You can also use:
ignore_user_abort(1);

Set whether a client disconnect should abort script execution


set_time_limit(0);

Limits the script maximum execution time, in this case it will run until the process finishes or the apache process restarts.


Notes

The php and the filename.php paths may be provided as a full-path, instead of php and filename.php, you can use /usr/bin/php and /full/path/to/filename.php.
Full Path is recommended to avoid file not found errors.

like image 198
Pedro Lobito Avatar answered Sep 23 '22 09:09

Pedro Lobito


the process may be closed when your session is closed.

try using nohup php filename.php

like image 35
mustafa Avatar answered Sep 23 '22 09:09

mustafa