How to handle PHP execution timeouts gracefully?

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

Threaded View
We have developed an open-source eCommerce sales forecasting add-on in
PHP (see link below) that requires usually more than a few seconds to
complete because the process involves some Web Services

Yet, in shared hosting with short PHP execution timeouts, our script
may not terminate (being killed by the web server).

Our concern is not the timeout in itself, it's the fact that this
situation is very confusing for the user who may not even be aware
that a timeout has been encountered and who may experience random bugs
due to this timeout.

Thus we need to handle gracefully the PHP execution timeouts by
displaying appropriate and meaningful error messages.

Do anyone knows how to do that?

Thanks in advance,
Joann├Ęs , sales forecasting

Re: How to handle PHP execution timeouts gracefully?

Quoted text here. Click to load it

Two solutions:

1) You said that some other web services are involved, so your program acts
as a sort of gateway between the remote client and those services.    Maybe the
504 error "Gateway timeout" of the HTTP protocol is appropriate in this case.

2) Using declare(), see
For example:

define("MAX_EXECUTION_TIME", 10); # seconds

$timeline = time() + MAX_EXECUTION_TIME;

function check_timeout()
    if( time() < $GLOBALS['timeline'] )

    # timeout reached:
    echo "<html><html>Sorry, we are very busy, retry later!</body></html>";


declare( ticks=1 ){
    # here the process that might require  
    # so much time; any output generated is
    # keep inside a string $s

# Ok, process completed, output the result:
echo $s;

/_|_\  Umberto Salsi

Re: How to handle PHP execution timeouts gracefully?

Thank you for your answer. We will what we can do with the declare()
method that you're suggesting.


Site Timeline