我有一个页面,让用户下载服务器立即为他们压缩的数据。这就是它的样子:
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);
虽然这可以很好地进行清理,但它引入了一个新问题:如果用户取消,压缩过程将继续。这毫无理由地浪费了计算机上的资源。
我如何保证清理工作顺利进行?
这应该每次都运行,即使在用户中止之后也是如此->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);
从未尝试过,但这可能会奏效:只需在压缩前使用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