如何压缩整个目录,并使用PHP下载[复制](How to zip a whole directory

2019-10-22 19:49发布

这个问题已经在这里有一个答案:

  • ZIP目录下的所有文件,并下载生成.ZIP 5回答

我自己学习PHP和我创建一个样本测试网站,它可以让用户输入要下载将被用来确定该文件夹的文件路径文件的代码。 我的代码下面有只下载一个文件。 我现在想的是下载和压缩整个目录。 请帮忙。 先感谢您

    <h3>Search Client File</h3>
            <form  method="post" action="#"  id="searchform">
              Type the Image Code:<br><br>
                  <input  type="text" name="icode">
            <br>
      <input  type="submit" name="submit" value="Search">
            </form>  

<?php
     $fcode=$_POST["icode"];
 if (!empty($fcode))
   {

$file="/var/www/website/$fcode.tif";

     if (file_exists($file))
     {

       header('Content-Description: File Transfer');
       header('Content-Type: application/octet-stream');
       header('Content-Disposition: attachment; filename='.basename($file));
       header('Content-Transfer-Encoding: binary');
       header('Expires: 0');
       header('Cache-Control: must-revalidate');
       header('Pragma: public');
       header('Content-Length: ' . filesize($file));
       ob_clean();
       ob_end_flush();
       readfile($file);

      }

      else
      {
        echo "The file $fcode.tif does not exist";
      } 
   }    

     else
     {
       echo "No Values";
     }

    ?>

Answer 1:

<?php

$dir = 'dir';
$zip_file = 'file.zip';

// Get real path for our folder
$rootPath = realpath($dir);

// Initialize archive object
$zip = new ZipArchive();
$zip->open($zip_file, 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();


header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename='.basename($zip_file));
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($zip_file));
readfile($zip_file);

?>

更多详情:

如何使用PHP来压缩整个文件夹



文章来源: How to zip a whole directory and download using php [duplicate]