【问题标题】:How to download a folder with all its folders and files without zipping it with php如何在不使用 php 压缩的情况下下载文件夹及其所有文件夹和文件
【发布时间】:2021-04-28 18:18:55
【问题描述】:

1 - 我有一个文件夹,里面有很多用户文件夹,每个用户的文件夹里面都有其他文件夹,里面有这样的图像:

  • localhost/cm/app/model/uploads/mark/3/small/car.jpg
  • localhost/cm/app/model/uploads/mark/3/big/car.jpg
  • localhost/cm/app/model/uploads/stiven/9/small/pc.jpg
  • localhost/cm/app/model/uploads/stiven/9/big/pc.jpg

2 - 我希望我下载这个文件夹及其所有内容。

3 - 如果无法使用任何名称压缩它,我更喜欢不使用相同名称压缩它来下载它。

4 - 我使用了此代码,但它不起作用,因为当我在下载后尝试打开 zip 文件夹时出现错误消息并告诉我“存档格式未知或已损坏”,这是我的代码:

<?php
$dir = 'http://localhost/cm/app/model/uploads'; //folder path

$archive = time().'download.zip';

$zip = new ZipArchive;
$zip->open($archive, ZipArchive::CREATE);
$files = scandir($dir);
unset($files[0], $files[1]);
foreach ($files as $file) {
$zip->addFile($dir.'/'.$file);
}
$zip->close();

header('Content-Type: application/zip');
header('Content-disposition: attachment; filename='.$archive);
header('Content-Length: '.filesize($archive));
readfile($archive);
unlink($archive);
?>

*那么如何在不压缩的情况下下载我的文件夹及其所有文件夹和图像?如果不可能,如何使用压缩?

【问题讨论】:

    标签: php zipfile


    【解决方案1】:

    我怀疑你的代码有错误。可能没有安装 ext-zip 一种检查方法是在终端中运行php -m,它将显示所有安装和启用的模块。

    如果您使用文本编辑器打开 zip 文件,就会出现错误消息而不是存档数据。

    【讨论】:

      【解决方案2】:

      这是我发现的最好方法:

       <?php
       // Get real path for our folder
       $rootPath = realpath('folder_for_ziping');
      
       // Initialize archive object
       $zip = new ZipArchive();
       $zip->open('file.zip', ZipArchive::CREATE | ZipArchive::OVERWRITE);
      
      // Create recursive directory iterator
      /** @var SplFileInfo[] $files */
       $files = new RecursiveIteratorIterator(
       new RecursiveDirectoryIterator($rootPath),
       RecursiveIteratorIterator::LEAVES_ONLY
      );
      
      foreach ($files as $name => $file)
      {
      // Skip directories (they would be added automatically)
      if (!$file->isDir())
      {
          // Get real and relative path for current file
          $filePath = $file->getRealPath();
          $relativePath = substr($filePath, strlen($rootPath) + 1);
      
          // Add current file to archive
          $zip->addFile($filePath, $relativePath);
        }
      }
      
      // Zip archive will be created only after closing object
      $zip->close();
      $archive = "file.zip";
      header('Content-Type: application/zip');
      header('Content-disposition: attachment; filename='.$archive);
      header('Content-Length: '.filesize($archive));
      readfile($archive);
      unlink($archive);
      ?>
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-03-14
        • 1970-01-01
        相关资源
        最近更新 更多