Page 1 of 1

Graceful expiration of maximum execution time

Posted: Sun Nov 30, 2008 11:50 am
by Robert K S
I have a database search script search.php, but on a sufficiently large database, some searches take forever, and I would like to limit the amount of time the script can run on the server before giving up.

I can put in a line like

set_time_limit(300);

but then the user who sees the script time out will receive an ugly black-and-white page that says

"Fatal error: Maximum execution time exceeded..."

This default error page can be confusing to the user, and it also gives away the server directory structure, which is, to say the least, not the preferred behavior.

How can I make an execution timeout more graceful? Can I replace or override the PHP default Fatal error page? Or is there some way to code the script such that I can achieve the same result as set_time_limit()?

Re: Graceful expiration of maximum execution time

Posted: Sun Nov 30, 2008 12:11 pm
by Eran
The only way I can think of is having the request sent by AJAX, and then error handling an incomplete response using Javascript.

This might off-topic, but there are probably optimizations the can improve the speed of the search. 300 seconds is way too long, regardless of the size of the database (unless we're talking really monster sizes here, in the 100's of GBs)

Re: Graceful expiration of maximum execution time

Posted: Sun Nov 30, 2008 12:24 pm
by mmj
The first thing that came to my mind was to do something like JavaScript's setTimeout function.

You can try checking the time before and after the resource intense moments.

Re: Graceful expiration of maximum execution time

Posted: Sun Nov 30, 2008 2:12 pm
by Mark Baker

Code: Select all

 
<?php
 
function shutdown()
{
   if (connection_timeout() == 1) {
      echo 'I have timed out';
      exit;
   }
   //  Do nothing, normal script termination
}
 
register_shutdown_function('shutdown');
 
?> 
 

Re: Graceful expiration of maximum execution time

Posted: Sun Nov 30, 2008 3:13 pm
by Robert K S
Thanks, Mark; only problem is that connection_timeout() is deprecated in newer versions of PHP. Better to use connection_status() and the connection-handling constants.

But I think this answers my question. I'll report back if I have further problems.