As a PHP developer, sometimes you would have to deal with long-running scripts. As you might know, in the php.ini file there is a setting called max_execution_time
which by default is set to 30 seconds. Meaning any particular script could only run for 30 seconds before it exits.
On some hosts, you can find it set to 60, 120, or even 300 seconds. But still, that might not be enough for some jobs you have to do.
PHP CLI
In these situations, one might possibly think to go for some CRON job scheduler for Linux, and probably run their script with the PHP CLI in the background. The beauty of PHP CLI SAPI is that its config’s maxe_execution_time
is set to 0, which means there is no restriction on how long your script will run.
But going the CRON way, you have next to no control over your process once you started it. Your only way to have some insight would be to set up some logging system, so the script could write its output there in the log files.
This is generally OK if you are dealing with some tasks like making background backups of your site or some scheduled CSV parsing etc. But when you want to have some UI and some direct insight into your processes, you have to take some other approach.
Background Process
Faced with some similar challenges recently, I decided to have a better look at what options there are already available in the PHP world. I came across this fantastic library called background-process. And I decided to build some nice wrapper around it so I could just plug it in some server and run commands as simple as inserting them in an HTML form.
You can find the script here. The usage is very simple:
- Run
composer install
to install the required dependency (background process library) - You can simply include the
Processor.php
file in your scripts. And use it as it is shown on the suppliedTest.php
file.
The main method of the class is the run()
method. It expects a valid command as an input/argument. For example, running some PHP script by issuing a command similar to: php -f ./YourFile.php
, or you have an option to use the bundled long-running example script: LongRunningPHPScript.php
. You can also run whichever shell command you like and is supported on the server. For example ls -la
or some python scripts like: python3 ./MyPythonScript.py
. It really doesn’t matter.
Requirements and showcase
The only requirement is that the shell_exec()
function is not disabled on your server. Otherwise, it won’t work.
Please check the simple screencast below for some showcase on how you may test the script by running the Test.php file.
Disclaimer:
Since this is a very powerful script it is important to be 100% sure where are you putting it and which kind of processes you would run. I shall not be held liable for any misuse or damages it may do to your data or your server.