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

时间:2015-11-12 12:36:09

标签: php process stream resource-cleanup

我有一个页面,我让用户下载服务器为他们拉链的数据。这是它的外观:

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);

虽然这可以很好地清理,但它引入了一个新问题:如果用户取消,则继续进行压缩过程。这无济于事地浪费了计算机上的资源。

我如何保证清理运行?

2 个答案:

答案 0 :(得分:0)

从未尝试过但也许这可行:只需在压缩前使用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

答案 1 :(得分:0)

这应该每次运行,即使在用户中止后 - > 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);