Starting a PHP script in the background?

Do you have a question? Post it now! No Registration Necessary.  Now with pictures!

Threaded View
What is the appropriate way to start a PHP script in the background? I
have a script that manipulates image data, and it takes a long time to
run. I'd like to send this process to the background at the appropriate
time, so that it can go do its job without holding up the user.

I've seen something like this used:

system("php myscript.php &");

But the PHP manual entry for the system() function call indicates the

"Note: If you start a program using this function and want to leave it
running in the background, you have to make sure that the output of
that program is redirected to a file or some other output stream or
else PHP will hang until the execution of the program ends."

I don't expect this background script to output anything, but suppose
an error occurs during execution? Will PHP get tied up as a result
(trying to output an error message)?

How do I properly execute a PHP script in the background from another
PHP script?

Thanks in advance!
Jonah Bishop

Re: Starting a PHP script in the background?

An noise sounding like Jonah Bishop said:
Quoted text here. Click to load it

system("php myscript.php & >> myscript.logfile");

Will append any output each time to myscript.logfile


Trees with square roots don't have very natural logs.
What's the difference between ignorance and apathy? Who knows? Who cares?

Re: Starting a PHP script in the background?

Jonah Bishop wrote:
Quoted text here. Click to load it

There are at least two ways of dealing with this issue:

1. Redirect the script's output into a file:

   system("php myscript.php & > myscriptlog.txt");
   system("php myscript.php & >> myscriptlog.txt");

  The former will write any output the script produces into
  a newly created file myscriptlog.txt; the latter will append
  output the script produces to myscriptlog.txt

2. Buffer the output at the beginning of the script and
   discard it at the end:

   // the script goes here...


Re: Starting a PHP script in the background?

NC wrote:

Quoted text here. Click to load it
almost right.
Quoted text here. Click to load it
wrong - this leaves stdout bound to the same file as the parent process so
will be ineffective.

Since the parent process must wait for a sig child, simply redirecting the
output is not a very clean solution. Really you want the new process to run
in a seperate session - its possible to this with fork() and
posix_setsid(), but a much simpler solution is to hand it off to daemon
like 'at':

`echo /usr/bin/php -q $my_php_script | at now`


Site Timeline