php download all files in directory

Solutions on MaxInterview for php download all files in directory by the best coders in the world

showing results for - "php download all files in directory"
Gabriela
30 Jun 2020
1Thanks to the help from @maxhud I was able to come up with the complete solution. Here is the final code snippet used to achieve my desired results:
2
3<?php
4/* creates a compressed zip file */
5function create_zip($files = array(),$destination = '',$overwrite = true) {
6  //if the zip file already exists and overwrite is false, return false
7  if(file_exists($destination) && !$overwrite) { return false; }
8  //vars
9  $valid_files = array();
10  //if files were passed in...
11  if(is_array($files)) {
12    //cycle through each file
13    foreach($files as $file) {
14      //make sure the file exists
15      if(file_exists($file)) {
16        $valid_files[] = $file;
17      }
18    }
19  }
20  //if we have good files...
21  if(count($valid_files)) {
22    //create the archive
23    $zip = new ZipArchive();
24    if($zip->open($destination,$overwrite ? ZIPARCHIVE::OVERWRITE : ZIPARCHIVE::CREATE) !== true) {
25      return false;
26    }
27    //add the files
28    foreach($valid_files as $file) {
29      $zip->addFile($file,$file);
30    }
31    //debug
32    //echo 'The zip archive contains ',$zip->numFiles,' files with a status of ',$zip->status;
33
34    //close the zip -- done!
35    $zip->close();
36
37    //check to make sure the file exists
38    return file_exists($destination);
39  }
40  else
41  {
42    return false;
43  }
44}
45
46
47
48$files_to_zip = array(
49  'upload/1_3266_671641323389_14800358_42187034_1524052_n.jpg', 'upload/1_3266_671641328379_14800358_42187035_3071342_n.jpg'
50);
51//if true, good; if false, zip creation failed
52$zip_name = 'my-archive.zip';
53$result = create_zip($files_to_zip,$zip_name);
54
55if($result){
56header('Content-Type: application/zip');
57header('Content-disposition: attachment; filename=filename.zip');
58header('Content-Length: ' . filesize($zip_name));
59readfile($zip_name);
60}
61?>