This is a short guide on how to create an infinite loop using PHP. In this post, I will create a simple WHILE loop that will run indefinitely.
Infinite WHILE loop.
Let’s take a look at the following example:
<?php //while 1 is equal to 1 while(1 == 1){ //do something }
The WHILE loop above will run indefinitely because the condition inside the brackets always equate to true. i.e. No matter what, one is always going to be equals to one.
Time limit issues.
Note that if you run the script above via your web server, you are likely to receive the following fatal error:
Fatal error: Maximum execution time of 120 seconds exceeded.
By default, PHP has a maximum execution time of 120 seconds. If your script violates the max_execution_time value that is defined in your the php.ini file, then PHP will throw a fatal error and your infinite loop will die.
To overcome this obstacle, you can use PHP’s set_time_limit function to remove this time limit:
<?php //If set to zero, no time limit is imposed. set_time_limit(0); //while 1 is equal to 1 while(1 === 1){ //do something }
It is important to point out that running a scripts like this on your web server is not recommended. In the past, loops like this have been known to cause memory and other resource-related issues.
You might also run into a situation where your web server initiates the timeout. For example: Apache has a directive / option called TimeOut, which has a default value of 300 seconds. Other web servers may also have their own default timeout values.
Ignoring aborted connections.
If the client disconnects, should your loop continue to run? If so, then you will need to use the ignore_user_abort function like so:
<?php //Ignore user aborts and allow the script to run indefinitely. ignore_user_abort(true); //If set to zero, no time limit is imposed. set_time_limit(0); //while 1 is equal to 1 while(1 === 1){ //do something }
As you can see, we told PHP to ignore user disconnects by passing a boolean TRUE value into ignore_user_abort. By default, PHP will kill the script if the client disconnects.
PHP Daemon.
As I mentioned above, running infinite PHP loops on your web server is not a good idea. In the vast majority of cases, it is better to create a PHP daemon. In case you didn’t already know, a daemon is a background process that can be automatically restarted if the process dies or the server is restarted.
Creating a PHP daemon using the likes of Supervisord or Upstart might save you a lot of headaches over the long term!