Background: My script recently behaved badly, hogging the server threatening to crash it. I am pretty sure it was due to an infinite loop, and I think I know how to safeguard against it. (The error was: Fatal error: Maximum execution time of 30 seconds exceeded. The code normally should finish in a second).

Issue: To avoid similar server impact, what else, if anything, need I learn about, (other than making sure potentially infinite loops are finite)?

I don't have a problem with errors generally, If my output turns ugly, so be it. I just can't afford the kind of malfunction that makes server admins unhappy.

    Well anything that causes massive server calls - so large loops, large data processing / functions.

    Massive Queries & badly formatted sql tables (ie duplicates and ill-advised keys) all have the potential to upset server admins!

    Best to have a local version of php, mysql on your own pc and test all code there, so you will know if anything may cause problems.

      Thanks - I handle limited amounts of data, so I guess for now keeping loops finite will be sufficient.

      I'll sprinkle die() over the script and hope for the best ;-)

        Maybe when testing the scripts have something like:

        set_time_limit(5);
        

        That way if infiinite loops do appear, they will only go for 5 seconds instead of 30 seconds. Then you can try to indentify the problem.

        Good Luck

          Good idea, but safe_mode is on :-(

            you could add a timer function i.e.:

            function utime() {
            	$time	= explode( ' ', microtime());
            	$usec	= (double)$time[0];
            	$sec	= (double)$time[1];
            	return $sec + $usec;
            	} 
            

            Then call the function before your loop:

            $start = utime();
            

            Then in the loop add some validation:

            $end = utime();
            $run = $end - $start;
            if($run > 5)
            {
              echo 'loop took longer than 5 seconds';
            die();
            }
            

            Haven't tested it but you should be able to debug any tricky loops.

              Write a Reply...