PHP脚本发送zip文件后无法删除

3
我有一个 PHP 脚本,用于允许用户下载一个包含多张图片的文件夹,以 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);
  }

任何帮助都将是极好的。


你可能想使用php zip类,而不是Unix命令zip,因为它更少跨平台。http://www.php.net/manual/en/book.zip.php - Clement Herreman
1个回答

0

我认为这是由于您的主机通过“强制”中断连接所致。脚本没有完成解析,因此unlink()不会发生。我过去也遇到过这个问题,所以您不能依赖脚本来删除文件。

您有几种解决方案。 您可以设置一个数据库,在那里保存下载信息,并创建一个cron任务来删除临时zip文件。

您还可以创建一个cron任务,检查filemtime()并在超过1天后删除。

最后一个选项是我的方法,但我对其进行了一些小调整,并创建了一些下载会话,以使另一个用户无法使用相同的下载链接。

您可以将unlink()与cron任务结合使用。


你的意思是脚本超过了php.ini允许的最大持续时间后被中断了吗? - Clement Herreman
这是一个可能的问题,因为我从来没有弄清楚为什么有时脚本不能完全执行。 - Mihai Iorga

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接