Press "Enter" to skip to content

Techy: Background Processes In PHP

From What You’re Doing Is Rather Desperate is a very nice way of running a background task in PHP. I’ve implemented compression of a .tar file in the following method using this code:


$ps=runinbackground("gzip -v $tarfile -c 1> ".$tmp."download.tar.gz 2>".$tmp."download.tar.log");
$count=0;
while (isprocessrunning($ps)) {
sendupdate(3,'overall','Compressing'.str_repeat('.',$count).$lastline);
$count++;
if ($count>8) { $count=0; }
sleep(1);
}
function runinbackground($command) {
#error_log($command);
$command="nohup $command & echo $!";
#error_log($command);
$PID=shell_exec($command);
return ($PID);
}
function isprocessrunning($PID) {
exec("ps $PID",$processstate);
return(count($processstate)>=2);
}

I can then monitor (within the loop) the download.tar.log file if necessary. Hope it helps someone else.

Be First to Comment

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.