Re: asynchronous launch of a script

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



On Tue, Jun 28, 2011 at 8:16 PM, David Harkness
<david.h@xxxxxxxxxxxxxxxxx>wrote:

> On Sun, Jun 26, 2011 at 7:42 PM, Tamara Temple <tamouse.lists@xxxxxxxxx
> >wrote:
>
> > How do I launch a php script from another running php script
> > asynchronously?
> >
>
> You can perform the long-running job in the same process that handles the
> request by sending appropriate headers. We use this to run reports that
> take
> ten minutes without making the user keep the browser tab open. Call this
> method before starting the job:
>
>    /**
>     * Effectively causes PHP to keep running after flushing everything and
> closing the client connection
>     *
>     * @param mixed $status JSON-encoded and sent to the client
>     */
>    public function flushAndCloseConnection($status) {
>        // disable any apache or php gzipping
>        if (function_exists('apache_setenv')) {
>            apache_setenv('no-gzip', 1);
>        }
>        ini_set('zlib.output_compression', 0);
>        // Tell the server and client we intend for it to disconnect
>        ignore_user_abort(true);
>        // Tell the client we are done!
>        header('Connection: close');
>        header('Content-type: application/json');
>        $json = json_encode($status);
>        header('Content-Length: ' . strlen($json));
>        echo $json;
>        flush();
>    }
>
> In our case we send a JSON status string ("ok") as well.
>

While this will work, I would caution against doing this, especially when
using Apache as the web server. Keeping an HTTP request handler process
occupied with an offline task is a substantial waste of resources. Far
better to offload that work to a separate process so as to free up the
request handler so it's available to handle another incoming request.

Another option is to fork the process using pcntl_fork() [1]. I haven't used
> this in PHP before so I can't give an example.
>

Forking an HTTP request handler can lead to some very unwelcome
side-effects. I'd urge you not to do this. It may appear to work for a
while, but I guarantee you'll live to regret it.

-Stuart

-- 
Stuart Dallas
3ft9 Ltd
http://3ft9.com/

[Index of Archives]     [PHP Home]     [Apache Users]     [PHP on Windows]     [Kernel Newbies]     [PHP Install]     [PHP Classes]     [Pear]     [Postgresql]     [Postgresql PHP]     [PHP on Windows]     [PHP Database Programming]     [PHP SOAP]

  Powered by Linux