how to circumvent a php 30 second time out

I have that 30 second max time limit on the servers php install problem, or sooner I have a problem with it. I wrote an atomStream parser but after 30 seconds the process is terminated by the server.
I don’t like writing code that fails on most servers (the 30 second limitation is standard for a php install), and I am not going to nag with my host about removing the limitation.

I am going to solve it in a different way : I wrote a routine a while ago that echo’s a javascript location.replace to the page in the html source, which forces the page to relocate to itself.

  1. $t=time();
  2. while(1) {
  3. //do stuff
  4. //…
  5.  if(time()>$t+25) {
  6.  echo "<script>\n";
  7.  echo "<!–\n";
  8.  echo "location.replace('".$_SERVER['PHP_SELF']."');";
  9.  echo "\n";
  10.  echo "–>\n";
  11.  echo "</script>\n";
  12.  echo "…";
  13.         flush();
  14.         exit;
  15.         }
  16. }
  17. exit;

Here’s a more practical one with an execution counter and a break

  1.  
  2. $run=$_GET['run']+1;
  3. $t=time();
  4. if($run>5) exit;
  5. while(1) {
  6. //do stuff
  7. //…
  8.  if(time()>$t+25) {
  9.  echo "<script>\n";
  10.  echo "<!–\n";
  11.  echo "location.replace('".$_SERVER['PHP_SELF']."?run=".$run."');";
  12.  echo "\n";
  13.  echo "–>\n";
  14.  echo "</script>\n";
  15.  echo "…";
  16.         flush();
  17.         exit;
  18.         }
  19. }
  20. exit;

That makes it keep count of how many times it ran, it cuts the while-loop after 25 seconds and runs 5 times.

Now I can grab 25 seconds of atomStream feed, probably 50 to 100 posts per run, then it terminates and restarts, and grabs another 25 seconds, runs all day. Ain’t perfect, but it works on any php install and should get me 200.000 posts a day, more than enough to be satisfied with the solution.

Posted in php and tagged .

3 Comments

  1. Hi!
    couldn’t you use a .htaccess file with
    php_value max_execution_time 60
    in it?
    cheers

  2. Hosts do not always allow me to use .htaccess or change php settings. After a few incidents where scripts just would not run on a limited account, I wanted a scripted solution that works independant of using IIS/ Apache server settings. This one ain’t a ‘killer’ solution, but it works independant. It also gives me the option to relocate a php page after sending headers.

  3. This is a neat way to do it.

    I would have done it using php’s inbuilt timoutout function, but you do make a case for relocating after sender headers.

    Keep up the good work

    Vanessa

Leave a Reply

Your email address will not be published. Required fields are marked *