jo**********@sa gitta-ps.com (John Ramsden) wrote
(in an article that hasn't yet turned up on my server):
I'm surprised there seems to be no direct way for PHP/Apache
to run a script that completes an HTTP request but can then
continue running, either indefinitely or as long as needed
to perform post-reply processing of some sort - kind of
"send reply now, but I still have some work to do before
exiting".
More rooting about on the web revealed that dozens of people
have asked the same question, but there is definitely no way
of doing this directly.
(It seems a reasonable requirement to me. But PHP internals
developers who have replied are dogmatic in their insistance
that it is a wrong thing to want to do, and I assume it will
never be supported.)
So, one must fall back on starting a background script. For
anyone who needs to do this, the following is an example I
have produced.
(I'd be interested if there is a more robust way to deduce
the OS platform, which works whether the script is run via
either HTTP or the command line, and I'd be very interested
if recent versions of PHP include an OS-independent function
for starting a background process!)
global $_SERVER;
if (array_key_exis ts ('argv', $_SERVER)) # Unix (HTTP or CLI)
{
proc_close (proc_open ("php jr_test_2.php &", array(), $foo));
}
else # Windows
{
# (_SERVER doesn't contain 'DOCUMENT_ROOT' record
# if the script is run from command line.
#
$path = array_key_exist s ('DOCUMENT_ROOT ', $_SERVER) ?
($_SERVER['DOCUMENT_ROOT'] . '/') : '';
proc_close (proc_open ("start /b php ${path}jr_test_ bg.php",
array(), $foo));
}
# Doesn't yet support other platforms, such as Macs
(At this point the background script jr_test_bg.php will be
running, and the script comprising the above code disconnects.
Needless to say the background script could be anything, e.g.
a perl script.)
Cheers
John R Ramsden (jo**********@s agitta-ps.cam) <-- com not cam