简体   繁体   中英

Create and download zip in PHP

I have the following code:

    // start downloading
    require_once 'classes/class-FlxZipArchive.php';

    $filename = 'update_'.time();

    $path = 'updates'.DIRECTORY_SEPARATOR.$update;

    $zip = new FlxZipArchive;

    $zip->open($filename.'.zip',ZipArchive::CREATE);

    $zip->addDir($path,basename($path));

    $zip->close();

    if(file_exists($filename.'.zip')){

        header("Content-type: application/zip"); 

        header("Cache-Control: public");

        header("Content-Description: File Transfer");

        header("Content-Disposition: attachment; filename=".$filename.".zip");

        header("Content-length: ".filesize($filename.'.zip'));

        header("Pragma: no-cache"); 

        header("Expires: 0"); 

        readfile($filename.'.zip');

        unlink($filename.'.zip');

    };

    exit;

This works, but the problem is: not the zip is downloaded, but an unzipped version of the zip. The zip is created and is visible on the server, but it downloads an unzipped version of the zip.

Let's say i have files.zip with the following content:

- folder
    - images
        - image1.png
        - image2.png
    - docs
        - doc1.docx
        - doc2.docx

Then the zip is created but not downloaded. Instead, a normal map with name 'folder' is downloaded (unzipped).

Where is my mistake?

I use the following class: https://gist.github.com/panslaw/4327882

Edit:

the code is working as expected, but I was using a mac with the settings to download and extract "save" files automatically. More info here: https://wiki.umbc.edu/pages/viewpage.action?pageId=31919091

Please try that code :

Html:

<div class='container'>
 <h1>Create and Download Zip file using PHP</h1>
 <form method='post' action=''>
  <input type='submit' name='create' value='Create Zip' />&nbsp;
  <input type='submit' name='download' value='Download' />
 </form>
</div>

Php

I have created includes folder within the project where I stored some files and folders.

Create Zip

Create ZipArchive Class object for Zip file creation. Define a function createZip() to read files and directory from the specified directory path.

If file

If the reading value is the file then add it to zip object using addFile() method.

If directory

If the value is directory then create an empty directory and call createZip() function where pass the directory path.

Download Zip

Check if zip file exists or not. If it exists then download and remove it from the server.

<?php 
// Create ZIP file
if(isset($_POST['create'])){
 $zip = new ZipArchive();
 $filename = "./myzipfile.zip";

 if ($zip->open($filename, ZipArchive::CREATE)!==TRUE) {
  exit("cannot open <$filename>\n");
 }

 $dir = 'includes/';

 // Create zip
 createZip($zip,$dir);

 $zip->close();
}

// Create zip
function createZip($zip,$dir){
 if (is_dir($dir)){

  if ($dh = opendir($dir)){
   while (($file = readdir($dh)) !== false){

    // If file
    if (is_file($dir.$file)) {
     if($file != '' && $file != '.' && $file != '..'){

      $zip->addFile($dir.$file);
     }
    }else{
     // If directory
     if(is_dir($dir.$file) ){

      if($file != '' && $file != '.' && $file != '..'){

       // Add empty directory
       $zip->addEmptyDir($dir.$file);

       $folder = $dir.$file.'/';

       // Read data of the folder
       createZip($zip,$folder);
      }
     }

    }

   }
   closedir($dh);
  }
 }
}

// Download Created Zip file
if(isset($_POST['download'])){

 $filename = "myzipfile.zip";

 if (file_exists($filename)) {
  header('Content-Type: application/zip');
  header('Content-Disposition: attachment; filename="'.basename($filename).'"');
  header('Content-Length: ' . filesize($filename));

  flush();
  readfile($filename);
  // delete file
  unlink($filename);

 }
}
?>

CSS

.container{
 margin: 0 auto;
 width: 50%;
 text-align: center;
}

input[type=submit]{
 border: none;
 padding: 7px 15px;
 font-size: 16px;
 background-color: #00a1a1;
 color: white;
 font-weight: bold;
}

Check that link

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM