I implemented a solution for PHP deamons about 2.5 years ago. My application runs in a closed environment and has only a few users. So scalability, performance and security was not really required.
I basically started my deamons as single PHP applications in CLI mode.
function startDeamon($daemonPath, $args = ""){
$phppath = "/../../php/php"; // points to php executable
$executionstring = $phppath." -f ".$daemonPath." ".$args;
execInBackground($executionstring);
}
function execInBackground($cmd){
if (substr(php_uname(), 0, 7) == "Windows"){
pclose(popen("start /B". $cmd, "r")); // Windows
} else {
exec($cmd . " > /dev/null &"); // Operating systems like unix
}
}
By calling startDaemon
with the path to your daemon script and the arguments you want to give it, a separate process is started on your web server. The process ends as soon as the daemon script terminates.
The arguments can be read in your daemon by accessing the $argv
array like so:
$myJobIs = $argv[1];
Keep in mind that this solution is very intensive on memory since every started process can take up like 5MB of RAM or more. (But it depends on your PHP installation, your system and your script)
And you also need to allow PHP to open new processes / run the exec function which might not be something you want to do.