php creating zips without path to files inside the zip

后端 未结 3 1908
无人共我
无人共我 2020-11-27 05:48

I\'m trying to use php to create a zip file (which it does - taken from this page - http://davidwalsh.name/create-zip-php), however inside the zip file are all of the folder

相关标签:
3条回答
  • 2020-11-27 06:08

    I think a better option would be:

    $zip->addFile($file,basename($file));
    

    Which simply extracts the filename from the path.

    0 讨论(0)
  • 2020-11-27 06:14

    The problem here is that $zip->addFile is being passed the same two parameters.

    According to the documentation:

    bool ZipArchive::addFile ( string $filename [, string $localname ] )

    filename
    The path to the file to add.

    localname
    local name inside ZIP archive.

    This means that the first parameter is the path to the actual file in the filesystem and the second is the path & filename that the file will have in the archive.

    When you supply the second parameter, you'll want to strip the path from it when adding it to the zip archive. For example, on Unix-based systems this would look like:

    $new_filename = substr($file,strrpos($file,'/') + 1);
    $zip->addFile($file,$new_filename);
    
    0 讨论(0)
  • 2020-11-27 06:22

    This is just another method that I found that worked for me

    $zipname = 'file.zip';
    $zip = new ZipArchive();
    $tmp_file = tempnam('.','');
    $zip->open($tmp_file, ZipArchive::CREATE);
    $download_file = file_get_contents($file);
    $zip->addFromString(basename($file),$download_file);
    $zip->close();
    header('Content-disposition: attachment; filename='.$zipname);
    header('Content-type: application/zip');
    readfile($tmp_file);
    
    0 讨论(0)
提交回复
热议问题