【问题标题】:Move or Delete and Force download of Archive after creation创建后移动或删除并强制下载存档
【发布时间】:2016-05-22 20:08:55
【问题描述】:

简单地说,我希望我的用户能够下载他们的网站文件,所以我创建了一个“下载网站”按钮,它使用这个脚本来添加他们目录中的所有文件/文件夹,该目录位于变量 @ 987654321@ 并归档这些文件/文件夹。

 <?
  ///////// 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,或者在完成下载后将其删除。

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

【问题讨论】:

  • 为什么要这样?您实际上没有任何东西可以将该 .zip 文件发送给用户。你只是在创造它。你也没有将任何路径信息放入$archiveName,所以你最终基本上只是foo.zip,然后zip会在当前执行环境的工作目录中创建它,该目录通常是主脚本文件所在的目录在。
  • 是的,我知道我没有添加任何代码来解决这些问题,因为我不确定需要添加哪些代码?

标签: php download directory archive


【解决方案1】:

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

 <?
  ///////// 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>';
}
  }
  ?>

这似乎解决了所有问题。

【讨论】:

    猜你喜欢
    • 2018-11-08
    • 2014-09-03
    • 2020-05-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-26
    • 1970-01-01
    • 2013-06-04
    相关资源
    最近更新 更多