send header and close connection, but still run additional code

From: Date: Thu, 01 May 2003 23:04:26 +0000
Subject: send header and close connection, but still run additional code
Groups: php.general 
Request: Send a blank email to php-general+get-146025@lists.php.net to get a copy of this message
Background info: Running PHP 4.1.2 with Apache 1.3.27 on Redhat 7.3. These are the latest errata updates for this OS from RedHat. I am working on a redirect script that sends the client a "Location" header via the header() function. This script needs to stay alive and do additional work after the header is sent (database work, log crunching, etc). Basically, the code looks like: <?php header("Location: http://remote.site/url"); ## Do my intensive work here... ... ... ?> The problem is that the header will not be sent until the entire script has finished. Mr. John W. Holmes (love that name btw ;) mentioned that I should use the register_shutdown_function() function to accomplish this. However, after doing some research along with my own testing, it seems that this function will still keep the connection open until the entire script is finished, thus making the redirect "slow". I found another possible solution that looks like: <? @set_time_limit(0); // Make sure there is no limit ob_start(); // Start output buffering header("Location: $url"); ob_flush(); // This sends the output to your browser ignore_user_abort(true);// Makes sure the script continues... // Do my work here ... ?> This sends the redirect right away, but has the side effect of killing the script completely, thus the rest of the work never gets run. My last resort is to move the additional work into a separate script and using this code: exec("php work_script.php '$argument' 2>/dev/null >&- <&- >/dev/null &"); This does what I need; ie, it does my work in the background while the location header is sent to the browser immediately. The obvious problem with this is that this would cause more load on the servers, as the OS needs to create an entire new process to run the code. We expect this script to be hit around 250-400K times a day. Thanks, Tony

« previous php.general (#146025) next »