0

How to open and close a process with PHP?

Right now I open a process with the following code:

$zoutput = array();
if( ($fp = popen("7za t \"".$path."\" * -r", "r")) ) {
    while( !feof($fp) ){
        $fread = fread($fp, 1024);
        $line_array = preg_split('/\n/',$fread);
    foreach($line_array as $a) {
        if($a != "") {
        $zoutput[] = $a;
        }
    }
        //$_SESSION['job'][$jobid]['currentfile'] = $_SESSION['job'][$jobid]['currentfile']+1;

        flush();
    }
    pclose($fp);
}

I'm looking into a solution to close the process in case the user want to abort. Even if I stop the php script, the process still runs in the background (and that's normal) but I can't find a way to close/terminate it under Windows.

Does anyone have an idea on how I can do that? Thank you.

EDIT to fit mallix's answer:

$zoutput = array();
    if( ($fp = popen("7za a -t7z ".$GLOBALS["backup_compression"]." \"".$_SESSION['job'][$jobid]['bFQN']."\" \"".$pathtobackup."\"", "r")) ) {
        while( !feof($fp) ){
                    //Verifying if the user want to abort the process
            if(isset($_SESSION['job'][$jobid]['AbortCurrentJob']) && ($_SESSION['job'][$jobid]['AbortCurrentJob'] == 1)) {
                pclose($fp);
                return;
            }
            $fread = fread($fp, 1024);
            $line_array = preg_split('/\n/',$fread);
            foreach($line_array as $a) {
                if($a != "") {
                    $zoutput[] = $a;
                }

            }
            //$_SESSION['job'][$jobid]['currentfile'] = $_SESSION['job'][$jobid]['currentfile']+1;

            flush();
        }
        pclose($fp);
    }
    echo json_encode($zoutput);

Unfortunatly the 7zip stanalone console process still run in the background. the value of the session variable is a 1 (integer) confirmed.

Edit ..:I just noticed that the request to change the session variable with jquery is waiting.... until the first script is complete. So, useless :(

Jeremy Dicaire
  • 4,615
  • 8
  • 38
  • 62

1 Answers1

0

In your php script, check every time if a specific session is set before looping again.
When user clicks ABORT terminate that session key.
This can also be implemented using database instead of sessions.

mallix
  • 1,399
  • 1
  • 21
  • 44
  • Thanks for the tip mallix. It's not too slow to check a $_SESSION variable each loop? And do you know if it's possible in any way to get more details about the command progress? – Jeremy Dicaire Jan 16 '13 at 18:57
  • 1
    No its not slow at all. You can count the lines parsed or even catch the last line parsed and inform back the user. – mallix Jan 16 '13 at 19:07
  • Done. (and thanks) But it's not working, the process still run in the background (Task Manager) – Jeremy Dicaire Jan 16 '13 at 19:38