如何压缩整个目录并使用php下载

时间:2015-04-26 03:06:38

标签: php file download header zip

我正在自学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";
     }

    ?>

1 个答案:

答案 0 :(得分:17)

<?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);

?>

阅读更多内容:

  

How to zip a whole folder using PHP