【问题标题】:php: Clean-up process remnants after user has canceledphp:用户取消后清理进程残留
【发布时间】:2015-11-12 12:36:09
【问题描述】:

我有一个页面让用户下载服务器立即为他们压缩的数据。看起来是这样的:

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

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

如何保证清理运行?

【问题讨论】:

标签: php process stream resource-cleanup


【解决方案1】:

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

【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 2015-01-31
      • 2015-08-27
      • 1970-01-01
      • 2020-10-19
      • 2010-09-23
      • 1970-01-01
      • 2012-10-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多