For quite some time I’ve searched for a way to start a command line script from within a page in PHP without using the crontab. Basically I just wanted to start a script which does some processing in the background. The solution is pretty simple, but it took me some time to find it.We all know the crontab: it can execute a script at a particular moment for you, based on what you define to be the moment. But what if you want to execute a background at the moment you would like to?
PHP defines four methods which can execute commands: exec, passthru, shell_exec and system. These methods wait for the script to finish and collect the output generated by that script. However, when a user leaves the page, closes his browser or stops the script, the background script which is executed is also stopped. To prevent this, people tend to use other options like pcntl or cURL. Using these extensions might offer a solution, but for simply starting a script they are much too verbose.
The solution presented is applicable in the situation where you just need to start a script and you don’t want users to be able to stop the script after starting. And the solution is….
The function ignore_user_abort().
By putting this function in front of a shell_exec execution, the script still starts the script executed by shell_exec. However, it doesn’t care any more if the user aborts the calling script. In my situation, the CLI script updates a status file and a progress file. When running, the status file contains an integer which denotes that the CLI script is running. This prevents the script from being run again while it’s already running. Furthermore, the progress file is updated so the progress can be checked by other scripts.