Graceful expiration of maximum execution time

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
Robert K S
Forum Newbie
Posts: 11
Joined: Thu Dec 18, 2003 7:06 pm
Location: Cleveland, Ohio

Graceful expiration of maximum execution time

Post 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()?
User avatar
Eran
DevNet Master
Posts: 3549
Joined: Fri Jan 18, 2008 12:36 am
Location: Israel, ME

Re: Graceful expiration of maximum execution time

Post 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)
mmj
Forum Contributor
Posts: 118
Joined: Fri Oct 31, 2008 4:00 pm

Re: Graceful expiration of maximum execution time

Post 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.
Mark Baker
Forum Regular
Posts: 710
Joined: Thu Oct 30, 2008 6:24 pm

Re: Graceful expiration of maximum execution time

Post 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');
 
?> 
 
Robert K S
Forum Newbie
Posts: 11
Joined: Thu Dec 18, 2003 7:06 pm
Location: Cleveland, Ohio

Re: Graceful expiration of maximum execution time

Post 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.
Post Reply