umm...just a comment: your adding infinite time out in your loop, in my exp with set_time_limit, setting it to 0 will give you weird result, like PHP ignoring it.
If your using 0 as your time limit dont put it in a loop, because if I create a script like:
foreach($blah as $blah)
{
set_time_limit(10);
}
this will ADD 10 seconds to the time limit, so if we loop 4 times, it has 40 seconds to execute (or so I've been told).
Plus if your using IIS, then set_time_limit MUST be lower than whats set in IIS