Ubuntu – Binding a php script with a apache startup script

apache-2.2PHPUbuntu

I want a php script to be executed when apache server starts and keeps on running till apache server stops.

How to bind a php script to apache startup script so that the script should be executed as soon as apache server starts.

Best Answer

I cannot see a way to bind directly to Apache startup script...

I will try by modifying the Apache startup script itself. This will requiere a little scripting job, but should be easy to implement.

Edit /etc/init.d/apache2

Find the case section like this one below, and start/stop your php script from here.

case $1 in
    start)
          start_myscript
          ...
          ...   
    stop)
         stop_myscript
         ...
         ...
    restart)
         stop_myscript
         ...
         start_myscript
    ...
    ...
    ...
esac

# Little functions for my script. Has to be placed before the CASE block

function start_myscript {
  nohup /path/to/php /path/to/script.php & # will run in background
}

function stop_myscript() {
  kill -9 $(pgrep -f "script.php")
}

Then in script.php you will have to implement an infinite loop to make it runs until Apache stops. Something like this :

<?php
    while(1) {
        Do stuff;
        sleep(10);
    }
?>