user782104
user782104

Reputation: 13545

500 internal server error when execute a simple PHP loop program?

<?php
set_time_limit(600);
while (1){
usleep(30000000);
}
?>

The php program above causing the 500 internal server error. The problem is , I have set the time limit as 600 -> 10 minutes. And I am expecting it will run for ten minutes, for 30 second each , it will run a while loop for 1 time, and keep the activity to 10 minute. However, it return 500 internal server error at round 2 minutes. What is the root cause / how to fix the problem ? thanks

Upvotes: 0

Views: 2852

Answers (2)

Eugen Mihailescu
Eugen Mihailescu

Reputation: 3711

I had a similar problem with usleep on a LAMP installation where PHP run in safe-mode.

So my suggestion is check if your PHP run on safe-mode. If that's the case try using the sleep function (although it won't help if you want to loop each 0.001s for instance).

Note also that usleep doesn't work on PHP Windows platforms until PHP 5.

I know this thread is old but I hope this check will help the others.

Upvotes: 0

TopherGopher
TopherGopher

Reputation: 673

I spun your code up on my own Linux-based web-server. I used a Linux server rather than IIS simply because I thought it would give me more debugging information. Your code for me works just fine. It doesn't time out. I would then have to say that there is something specific to IIS. I would check the Event Log. A 500 error should have something interesting in there. To get to the event log (http://msdn.microsoft.com/en-us/library/ms524984(v=vs.90).aspx):

  • From the Start menu, click Run. In the Open box, type eventvwr. Click OK.
  • Event Viewer is listed under the System Tools node.

I would suggest, if you need this program to wait for 10 minutes, either go into your PHP.ini file (if that's the problem) and up the max_execution_time by A LOT, or as an alternative, let the page sit for 10 seconds and then reload the same page with header(). The advantage to this approach is that you aren't killing EXTRA CPU cycles by just spinning and locking everything up. You are instead just re-querying your server and using a persistent cookie:

<?php
echo "Time Slept: ".$_COOKIE['total_time_slept']; //persistent variable you can use to measure how much time has elapsed
if($_COOKIE['total_time_slept'] < 1000) //if less than 10 minutes
{     
    $page = $_SERVER['PHP_SELF'];
    $sec = 10;        
    setcookie('total_time_slept', $_COOKIE['total_time_slept']+$sec); //append that time to the counter
    header("Refresh: $sec; url=$page"); //reload this page every 10 seconds
}
?>

Upvotes: 3

Related Questions