PHP脚本发送zip文件并在不工作后删除

标签 php zip

我有这个 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/

相关文章:

php - MYSQL 结果格式化

php - Laravel 出现错误 undefined variable

php - 客户端/服务器/数据库。我应该关心 utf-8 以外的其他字符集吗?

php - 按最新日期排序文件在顶部使用 RecursiveDirectoryIterator

date - Linux zip 命令 - 在文件名中添加日期元素

java - 从ZIP文件中获取字节[]

javascript - RSA-OAEP SHA-512 从 Javascriptwebcrypt api 加密/解密到 PHP openssl?

java - 为什么我的测试文件系统只能在内存中工作?

java - 未添加 NETBEANS 项目警告

php - 如何压缩整个目录并使用php下载