Search code examples
phpcroncommand-line-interfacelong-running-processes

Prevent long running PHP script from closing


I'm running a php script via cli, so it can run in background. This script is suposed run 24/7. How can I prevent it from shutting down (on errors, warnings, etc) and restart immediatly if it happens?

Thanks in advance!


Solution

  • You could use a shell script to call php in an infinite loop, and run the shell script in the background. For example (a bit simplistic) a script like this, say "runloop.sh":

    #!/bin/bash
    # Run php script in a loop
    while true; do
      php phpscript.php
    done;
    

    ...and then run that script in the background, or from init. From the command prompt:

    $ ./runloop.sh &
    

    ...to run the script in the background. It should run forever, unless you kill it somehow.


    I should add that you'll need to make the shell script executable:

    $ chmod +x runloop.sh