php: 用户取消后清理进程残留

php: Clean-up process remnants after user has canceled

我有一个页面,我可以让用户下载服务器立即为他们压缩的数据。这是它的样子:

createFilesList(); //  <---- creates a text list of files do be zipped

header('Content-Type: application/zip');
header('Content-disposition: attachment; filename="'.$downloadFilename.'');

$fp = popen('cat '.$fullListOfFiles.' | sudo -u myuser zip -@ -9 - ', 'r');

$bufsize = 8192;
$buff = '';
while( !feof($fp) ) 
{
    $buff = fread($fp, $bufsize);
    echo $buff;
}
pclose($fp);

doClean(); //  <----- deletes the list of files

问题:如果用户下载文件,清理工作正常。但是,如果用户取消下载,列表将保持原状!

其他帖子的失败解决方案:其他帖子建议了这个解决方案:

ignore_user_abort(true);

虽然这可以很好地清理,但它引入了一个新问题:如果用户取消,压缩过程将继续。这无缘无故地浪费了计算机资源。

如何保证清理运行?

从未尝试过,但也许这可行:只需在压缩前使用 connection_aborted() 进行测试。

createFilesList(); //  <---- creates a text list of files do be zipped

header('Content-Type: application/zip');
header('Content-disposition: attachment; filename="'.$downloadFilename.'');

if(0 ==connection_aborted())
{
    $fp = popen('cat '.$fullListOfFiles.' | sudo -u myuser zip -@ -9 - ', 'r');

    $bufsize = 8192;
    $buff = '';
    while( !feof($fp) ) 
    {
        $buff = fread($fp, $bufsize);
        echo $buff;
    }
    pclose($fp);
}


doClean(); //  <----- deletes the list of files

每次都应该 运行,即使在用户中止后也是如此 -> register_shutdown_function http://php.net/manual/en/function.register-shutdown-function.php

// register a shutdown cleanup
register_shutdown_function('doClean');

createFilesList(); //  <---- creates a text list of files do be zipped

header('Content-Type: application/zip');
header('Content-disposition: attachment; filename="'.$downloadFilename.'');

$fp = popen('cat '.$fullListOfFiles.' | sudo -u myuser zip -@ -9 - ', 'r');

$bufsize = 8192;
$buff = '';
while( !feof($fp) ) 
{
    $buff = fread($fp, $bufsize);
    echo $buff;
}
pclose($fp);