创建后移动或删除并强制下载存档

Move or Delete and Force download of Archive after creation

简而言之,我希望我的用户能够下载他们的网站文件,所以我创建了一个 "Download Website" 按钮,它使用此脚本将所有 files/folders 添加到他们的目录中在变量 $direc 中并归档那些 files/folders.

 <?
  ///////// DOWNLOAD ENTIRE WEBSITE:
  if(isset($_POST['download_site'])){
      // define some basics
$rootPath = '../useraccounts/'.$direc.'';
$archiveName = ''.$direc.'.zip';

// initialize the ZIP archive
$zip = new ZipArchive;
$zip->open($archiveName, ZipArchive::CREATE);

// create recursive directory iterator
$files = new RecursiveIteratorIterator (new RecursiveDirectoryIterator($rootPath), RecursiveIteratorIterator::LEAVES_ONLY);

// let's iterate
foreach ($files as $name => $file) {
    $filePath = $file->getRealPath();
    $zip->addFile($filePath);
}

// close the zip file
if (!$zip->close()) {
    echo '<p>There was a problem writing the ZIP archive.</p>';
} else {
    echo '<p>Successfully created the ZIP Archive!</p>';
}
  }
  ?>

令我惊讶的是,这段代码有效。虽然,有一些小问题:

  1. 它不会自动强制下载该存档。
  2. 它将存档添加到我的主目录,而不是将其移动到我选择的单独目录,例如 site_downloads,或者在完成下载后将其删除。

这些问题完全可以解决吗?如果不能,是否有更好的方法来避免我的主目录被持续下载填满?我想一旦多次创建存档会导致问题,因为它使用目录名称。

通过使用几种不同的组合解决了这个问题:

 <?
  ///////// DOWNLOAD ENTIRE WEBSITE:
  if(isset($_POST['download_site'])){
      // define some basics
$rootPath = '../useraccounts/'.$direc.'';
$archiveName = ''.$direc.'.zip';

// initialize the ZIP archive
$zip = new ZipArchive;
$zip->open($archiveName, ZipArchive::CREATE);

// create recursive directory iterator
$files = new RecursiveIteratorIterator (new RecursiveDirectoryIterator($rootPath), RecursiveIteratorIterator::LEAVES_ONLY);

// let's iterate
foreach ($files as $name => $file) {
    $filePath = $file->getRealPath();
    $zip->addFile($filePath);
}


// close the zip file
if (!$zip->close()) {
    echo '<p>There was a problem writing the ZIP archive.</p>';
} else {
    rename($archiveName, 'user_archives/'.$archiveName.'');
    $yourfile = "user_archives/".$archiveName."";

    $file_name = basename($yourfile);

    header("Content-Type: application/zip");
    header("Content-Disposition: attachment; filename=$file_name");
    header("Content-Length: " . filesize($yourfile));

    readfile($yourfile);
    ignore_user_abort(true);
if (connection_aborted()) {
    unlink('user_archives/'.$archiveName.'');
} else {
    unlink('user_archives/'.$archiveName.'');
}
    echo '<p>Successfully created the ZIP Archive!</p>';
}
  }
  ?>

这似乎解决了所有问题。