将文件夹和文件添加到zip(PHP)

时间:2017-01-18 21:01:19

标签: php

我希望将匹配数组中的文件夹和文件添加到zip文件中。以下是我的代码:

function listdir($start_dir='./assets') {
  //Array that will contain the director
  $files = array();

  if (is_dir($start_dir)) {
    $fh = opendir($start_dir);
    while (($file = readdir($fh)) !== false) {
      // Loop through the files, skipping '.' and '..', and recursing if necessary
      if (strcmp($file, '.')==0 || strcmp($file, '..')==0) continue;
      $filepath = $start_dir . '/' . $file;
      if ( is_dir($filepath) )
        $files = array_merge($files, listdir($filepath));
      //else
        array_push($files, $filepath);
    }
    closedir($fh);
  } else {
    // false if the function was called with an invalid non-directory argument
    $files = false;
  }
  return $files;
}

//Array of all files
$allFiles = listdir('./assets');
print_r($allFiles);

//Gets all values with name "asset"
$name = $_POST['asset'];

//If there are items in the array, zip them together
if($name!=0){
  //Compares $_POST array with array of all files in directory
  $result = array_intersect($allFiles, $name);

  function zipFilesAndDownload($result){
  $zip = new ZipArchive();
  //create the file and throw the error if unsuccessful
  if ($zip->open('SelectedAssets.zip', ZIPARCHIVE::CREATE )!==TRUE) {
      exit("cannot open SelectedAssets.zip\n");
  }
  //add each files of $file_name array to archive
  foreach($result as $allFiles)  {
      $zip->addFile($allFiles);     
  }

  $zip->close();
  $zipped_size = filesize('SelectedAssets.zip');
  header("Content-Description: File Transfer");
  header("Content-type: application/zip"); 
  header("Content-Type: application/force-download");// some browsers need this
  header("Content-Disposition: attachment; filename=SelectedAssets.zip");
  header('Expires: 0');
  header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
  header('Pragma: public');
  header("Content-Length:". " $zipped_size");
  ob_clean();
  flush();
  readfile("SelectedAssets.zip");
  unlink("SelectedAssets.zip"); // Now delete the temp file (some servers need this option)
      exit;   
    }
  if(isset($_POST['submit'])) {
  //$file_names=$_POST['assets'];// Always sanitize your submitted data!!!!!!
  //$file_names = filter_var_array($_POST['assets']);//works but it's the wrong method
  $filter = filter_input_array(INPUT_POST, FILTER_SANITIZE_SPECIAL_CHARS) ;
  $file_names = $filter['assets'] ; 
  //Archive name
  $archive_file_name='DEMO-archive.zip';
  //Download Files path
  $file_path= getcwd(). './';
  //call the function
  zipFilesAndDownload($result);
  } else {

  print 'Something went wrong.';
  exit;
  }
} //Otherwise, don't.
else {
  print_r("Please select a file.");
}

上面的代码搜索目录并读取所有文件夹和文件。然后使用array_intersect,我将用户放入空数组的文件与先前搜索到的目录中的所有文件进行匹配。然后我压缩匹配并下载的文件。

我的问题是,如何将文件夹添加到此zip文件中?截至目前,这只添加文件和文件夹被假定为空。

0 个答案:

没有答案