简体   繁体   中英

PHP Script to send zip file and delete after not working

I have this PHP Script which is run to allow a user to download a folder of images in a zip, it is meant to create the zip and send it to the user and then delete it from the server. It works fine yet except sometimes it doesn't delete the zip. Any ideas?

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

Any help would be great.

I believe this happens when connection is interrupted by "force" by your host. the script doesn't finish the parsing so unlink() doesn't occur. I had this problem in the past so you cannot rely on your script to delete the file.

You have several solutions. You can setup a database and save download info there and make a cron task to delete the temp zip.

You can make a cron also and check the filemtime() and delete if older than 1 day.

The last option was my approach, but I made some little adjustments to it and made some download sessions in the way that another user couldn't use same download link.

You can combine your unlink() with a cron task.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM