<?php
while(true){
//code goes here.....
}
?>
I want to make a PHP web server, so how can I make this script run forever with Curl?
Don't forget to set maximum execution time to infinite(0).
Better make sure you don't run more than one instance, if that's your intention:
ignore_user_abort(true);//if caller closes the connection (if initiating with cURL from another PHP, this allows you to end the calling PHP script without ending this one)
set_time_limit(0);
$hLock=fopen(__FILE__.".lock", "w+");
if(!flock($hLock, LOCK_EX | LOCK_NB))
die("Already running. Exiting...");
while(true)
{
//avoid CPU exhaustion, adjust as necessary
usleep(2000);//0.002 seconds
}
flock($hLock, LOCK_UN);
fclose($hLock);
unlink(__FILE__.".lock");
If in CLI mode, just run the file.
If in another PHP on a webserver, you could start the one which must run infinetely like this (instead of using cURL, this eliminating a dependency):
$cx=stream_context_create(
array(
"http"=>array(
"timeout" => 1, //at least PHP 5.2.1
"ignore_errors" => true
)
)
);
@file_get_contents("http://localhost/infinite_loop.php", false, $cx);
Or you could start from linux cron using wget like this:
`* * * * * wget -O - http://localhost/infinite_loop.php`
Or you could start from Windows Scheduler using bitsadmin running a .bat file which contains this:
bitsadmin /create infiniteloop
bitsadmin /addfile infiniteloop http://localhost/infinite_loop.php
bitsadmin /resume infiniteloop
For a php code to run forever, it should have the ff.:
set_time_limit(0);
// so php won't terminate as normal, if you will be doing stuff that will take a very long processing timesetInterval()
, setTimeout()
EDIT: But since you will be setting up a cron job then you can keep away from the client-side handling.
EDIT: My suggestion, is not to use infinite loops unless you have a code that tells it to exit the loop after some time. Remember, you will be calling the same page using a cron job, so there is no point in keeping the loop infinite. [edit] Otherwise, you will be needing a locking system as suggested by @Tiberiu-Ionuț Stan so only 1 instance may run each time the cron job is called.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With