How to zip a whole directory and download using php

29,310
<?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);

?>

Read more at:

How to zip a whole folder using PHP

Share:
29,310
Xander Vane
Author by

Xander Vane

Updated on July 09, 2022

Comments

  • Xander Vane
    Xander Vane almost 2 years

    I am self studying php and I am creating a sample test site which lets the user input the file code which will be used to determine the file path of the folder to be downloaded. The code i have below will only download a single file. What i want now is to download and zip the whole directory. Please help. Thank you in advance

        <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";
         }
    
        ?>
    
  • Xander Vane
    Xander Vane about 9 years
    Hi I just replaced the whole php code and the file path, then when i refreshed the tabs on my page is no longer present, plus when i hit submit button on my page it doesnt shoe anything
  • Adrian Cid Almaguer
    Adrian Cid Almaguer about 9 years
    @XanderVane try the code, it works, you should not put html code before this code because the code send to the broswer headers
  • Xander Vane
    Xander Vane about 9 years
    It works!!! Thank you very much! :) I just separated the html code into a different file and the php code to a php file.
  • Adrian Cid Almaguer
    Adrian Cid Almaguer almost 9 years
    @XanderVane you're welcome, and good luck in your work ;-)
  • drooh
    drooh over 5 years
    Is there a way to have this exclude certain files and directories?
  • OnklMaps
    OnklMaps over 5 years
    Is there a way to make the zip also contain the directory, not just the directory contents?
  • Adrian Cid Almaguer
    Adrian Cid Almaguer over 5 years
    @OnklMaps if you go a level up then you can zip the directory.