How to add files to newly created folder in ziparchive using php?

余生颓废 提交于 2020-08-19 10:18:49

问题


enter image description here

As in the image above ,I have images that are organized in virtual folders(in mysql database but not real folders). I need to make the selected folder available for download as zip .I was able to zip the images but how can we add subdirectory so as to add images to it (i tried using addEmptyDir() but couldn't figure out a way to add images into it! ). Is this really possible without creating the physical folder?

Please suggest!


回答1:


Thanks @dnagirl for your answer, but I was actually looking for a way to add files inside subfolders (maybe I was unable to make myself clear!)

discovered that zipArchive automatically creates folder if we give 'path/to/filename' instead of just 'filename'

This is how I achieved it in case anybody may need it!

function zipFilesAndDownload($file_names,$archive_file_name,$img_localpath)
{
  $folder_path=WSP_AK_PLUGIN_DIR ."akTempFolder/";
  $zip = new ZipArchive();
  if ($zip->open($folder_path.$archive_file_name, ZIPARCHIVE::CREATE )===TRUE) {
    //$zip->addEmptyDir('myimages');(this was what i thought would create folder!)
    foreach($file_names as $files)
    {
        //$zip->addFile($img_localpath.'/'.$files, 'myfolder/'.$files);
        $zip->addFile($img_localpath.'/'.$files['fileName'],    $files['folder_path'].$files['fileName']);
    }
    $zip->close();

in above code $files['folder_path'] will give the path to file where it will be created For eg folder1/folder2/image1.jpg

    header("Content-type: application/zip"); 
    header("Content-Disposition: attachment; filename=$archive_file_name");
    header('Content-Type: application/force-download');
    header('Content-Length: ' . filesize($folder_path.$archive_file_name));
    header("Pragma: no-cache"); 
    header("Expires: 0");
    if( file_exists($folder_path.$archive_file_name)) {
        ob_clean();
        readfile($folder_path.$archive_file_name);
    }
    unlink($folder_path.$archive_file_name);
  }
}



回答2:


If the "files" you want to add to your zip directory are stored in a db as strings, you could use ZipArchive::addFromString. If the db stores pointers to actual files use ZipArchive::addFile



来源:https://stackoverflow.com/questions/11933753/how-to-add-files-to-newly-created-folder-in-ziparchive-using-php

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!