Although the Halayem Anis solution is very creative, I find it important to note that you can never be sure that the PHP script continues to run in the background. Therefore, if you decide to run your script in "Apache start", then you will probably end up resetting Apache quite often, just reload the script.
I assume that even when you come to this question, as on a regular server, you will never have to touch the Apache reset button. It starts at system startup and then starts. If so, you can simply run the php myscript.php at startup.
Given that there is no way to ensure that the script continues to work, I would use a different approach, where I check if it is running, and if not, restart it.
So, the first step is to enable you to track if the script is working. I would go for a simple approach when your myscript.php writes one byte to a file every 5 seconds or so. That way I can use the last modified time for the file to see it still works, because last modified time + 5 seconds < now == not running .
You can also save the last access time to the database every 5 seconds or so. It may be a little faster than accessing files if you have a lot of traffic.
The second part is for each request to check if the script is working. For these two works, I would use PHP.ini to add a PHP script for each request. You can do this with the auto_append_file option.
This preend script will work as follows:
<?php $filename = 'checkonline.txt'; $cmd = "php myscript.php"; if (filemtime($filename)+5<time()) { //run in background without freezing php //based on code posted on PHP exec manual, linked below if (substr(php_uname(), 0, 7) == "Windows"){ pclose(popen("start /B ". $cmd, "r")); } else { exec($cmd . " > /dev/null &"); } } ?>
Make sure filemtime and exec work and what you need to keep in mind. They are slightly different on Windows / * nix.
Hugo delsing
source share