Run a php script in background on debian (Apache) Run a php script in background on debian (Apache) apache apache

Run a php script in background on debian (Apache)


  1. You could run the script with the following command:

    nohup php /var/www/development_folder/scripts/push2/push.php > /dev/null &

    The nohup means that that the command should not quit (it ignores hangup signal) when you e.g. close your terminal window. If you don't care about this you could just start the process with "php /var/www/development_folder/scripts/push2/push.php &" instead. PS! nohup logs the script output to a file called nohup.out as default, if you do not want this, just add > /dev/null as I've done here. The & at the end means that the proccess will run in the background.I would only recommend starting the push script like this while you test your code. The script should be run as a daemon at system-startup instead (see 4.) if it's important that it runs all the time.

  2. Just type

    ps ax | grep push.php

    and you will get the processid (pid). It will look something like this:

    4530 pts/3    S      0:00 php /var/www/development_folder/scripts/push2/push.php

    The pid is the first number you'll see. You can then run the following command to kill the script:

    kill -9 4530

    If you run ps ax | grep push.php again the process should now be gone.

  3. I would recommend that you make a cronjob that checks if the php-script is running, and if not, starts it. You could do this with ps ax and grep checks inside your shell script. Something like this should do it:

    if ! ps ax | grep -v grep | grep 'push.php' > /dev/nullthen  nohup php /var/www/development_folder/scripts/push2/push.php > /dev/null &else  echo "push-script is already running"fi
  4. If you want the script to start up after booting up the system you could make a file in /etc/init.d (e.g. /etc.init.d/mypushscript with something like this inside:

    php /var/www/development_folder/scripts/push2/push.php

    (You should probably have alot more in this file)

    You would also need to run the following commands:

    chmod +x /etc/init.d/mypushscriptupdate-rc.d mypushscript defaults

    to make the script start at boot-time. I have not tested this so please do more research before making your own init script!