p2p.wrox.com Forums

Need to download code?

View our list of code downloads.

  Return to Index  

beginning_php thread: Infinite Loops

Message #1 by "Gerry Vandermaesen" <gerry@a...> on Wed, 23 Oct 2002 18:32:24 +0200
Hi all,

When a PHP scripts gets into an infinite loop my server's resources are
used up and eventually the computer completely freezes. Therefore I have
two questions:

1) Is it possible to secure the server so that infinite loops don't lock
up the system? Apparently the timelimit of 30 secs and the memory usage
limit for a script in php.ini don't do the trick.
2) What would be a good practice to avoid infinite loops in scripts in
the first place?

My configuration is:

Windows 2000 Pro, Apache 2.0.43, PHP 4.2.3 running as a CGI.



Message #2 by "Nikolai Devereaux" <yomama@u...> on Wed, 23 Oct 2002 09:43:44 -0700
As far as infinite loops are concerned, there's not that much you can do other
than count on php.ini's threshold limits.

This sounds pretty lame, but the best practice to avoid infinite loops is to
make sure that your loop exiting condition MUST occur.  Do not change the value
of your loop control variable inside the body of the loop.  Double check your
logic.  Standard practice anywhere, really -- think about the logic of the code
an extra minute before you jot it down.


for($i = someval; $i < otherval; ++$i)
  // use $i in here if you need to, but
  // don't _ever_ change its value!

while($x != $y)
  // something in here must change $x OR $y,
  // maybe both (but I don't recommend it)
  // and guarantee that $x will eventually
  // == $y.

Another type of loop that many programmers find useful is an explicitly
infinite loop, where the exit code appears within the body of the loop.  The
same rules apply -- namely, you must guarantee that the condition will be met
to exit the loop:

    // ...
    if(<condition>)  break;
    // ...

take care,


  Return to Index