Question

I'm trying to export quite a large amount of data from a database into an Excel file. The problem I have with my methodology is that it takes too long, and the script ends up timing out.

I have been thinking of a way to run my script in the background, but as I want my code to be as flexible as possible, I would prefer avoid using exec() which is often disabled on shared hosting environments, and to support at least PHP 5.2+. I have been trying to run my script via PHP cURL, however such solution does not seem to be very elegant.

I am unsure whether at this point I should provide any code (I am just testing out any possible solution, so everything I wrote is very raw) as I am only looking for somebody to point me to the right direction – I'm willing to do my bit of reading.

Thank you very much for your help :)

Was it helpful?

Solution

The process will continue to run in Apache, but this is a portable solution you can kick off easily with an AJAX request from a browser if you want.

http://quickshiftin.com/blog/2011/04/non-blocking-web-service-processing-in-php/

<?php
// this script can run forever
set_time_limit(0);
 
// tell the client the request has finished processing
header('Location: index.php');  // redirect (optional)
header('Status: 200');          // status code
header('Connection: close');    // disconnect
 
// clear ob stack 
@ob_end_clean();
 
// continue processing once client disconnects
ignore_user_abort();
 
ob_start();
/* ------------------------------------------*/
/* Message you'll send to client goes here ..*/
/* ------------------------------------------*/
$iSize = ob_get_length();
header("Content-Length: $iSize");
 
// if the session needs to be closed, persist it
// before closing the connection to avoid race
// conditions in the case of a redirect above
session_write_close();
 
// send the response payload to the client
@ob_end_flush();
flush();
 
/* ------------------------------------------*/
/* PHP Excel Job goes here ...               */
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top