我有这个 PHP 脚本,运行它允许用户下载 zip 中的图像文件夹,它的目的是创建 zip 并将其发送给用户,然后从服务器上删除它。它工作正常,但有时它不会删除 zip。有什么想法吗?
$filename_no_ext=$_GET['zip'];
// we deliver a zip file
header("Content-Type: archive/zip");
// filename for the browser to save the zip file
header("Content-Disposition: attachment; filename=$filename_no_ext".".zip");
// get a tmp name for the .zip
$tmp_zip = tempnam ("tmp", "tempname") . ".zip";
// zip the stuff (dir and all in there) into the tmp_zip file
`zip -r $tmp_zip $filename_no_ext`;
// calc the length of the zip. it is needed for the progress bar of the browser
$filesize = filesize($tmp_zip);
header("Content-Length: $filesize");
// deliver the zip file
$fp = fopen("$tmp_zip","r");
echo fpassthru($fp);
fclose($fp);
// clean up the tmp zip file
//`rm $tmp_zip `;
unlink($tmp_zip);
//If user aborts check they have and then clean up the zip
ignore_user_abort(true);
echo "\n";
if (connection_status()!=0){
unlink($tmp_zip);
}
if (connection_aborted()) {
unlink($tmp_zip);
}
任何帮助都会很棒。
最佳答案
我相信当连接被您的主机“强行”中断时会发生这种情况。脚本没有完成解析,所以 unlink()
不会发生。我过去遇到过这个问题,所以你不能依赖你的脚本来删除文件。
您有多种解决方案。 您可以设置数据库并在其中保存下载信息,并执行 cron 任务以删除临时 zip。
您也可以创建一个 cron 并检查 filemtime()
并在超过 1 天时将其删除。
最后一个选项是我的方法,但我对其进行了一些小的调整,并以其他用户无法使用相同下载链接的方式进行了一些下载 session 。
您可以将您的 unlink()
与 cron 任务结合起来。
关于PHP脚本发送zip文件并在不工作后删除,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7157991/