Run Scripts in Separate Threads in PHP
I’ve been working on a new project over the past few weeks and one of the requirements of the system was to update a number of records in the database based off the data stored in a large quantity of XML files that would be stored on an external CDN. While initially this didn’t seem a problem, once the number of records grew that were required to be updated it became obvious that doing the updates sequentially wasn’t going to work, and as I didn’t have the required extensions to use pcntl-fork I had to come up with another way to launch multiple updates simulatenously, which turned out to be much simpler than I had thought but took a bit of searching to find:
<?php
exec("nohup /usr/local/bin/php -f /path/to/script/file.php parameterValue > /dev/null &");
?>
This will execute the PHP script stored in file.php in its own thread but the PHP script calling it will not have to wait on it finishing execution as it would be if you called the script without the nohup and > /dev/null &. This solution will only work on *nix systems as opposed to Windows, but I imagine there is probably a way to do it in Windows too. The downside to this is that you will not be able to get any return value from the script, therefore it is only of any use if you need to run a task that does not require the calling file to get the results back. You can however pass data to the script as I have done in the example above, the value “parameterValue” would be available to file.php via $argv[1], for example:
<?php /* -- file.php -- */ echo 'The value '.$argv[1].' was passed to me via a CLI command.'; ?>

After many months of analysis, research, design, development and testing I have decided to open