简体   繁体   中英

Unable to create flat zip file with PHP's ZipArchive

I'm trying to create a zip file with a flat folder/file structure with PHP ZipArchive that contains two PDF files. So basically both files should be in the root of the zip file. I use the code below to create the zipfile.

$zip = new ZipArchive();

$zip_filename = "zipfile.zip";

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

$zip->addFile("cover_file.pdf", "cover_file.pdf");
$zip->addFile("inlay_file.pdf", "cover_file.pdf");              
$zip->close();

Whatever I do, the files are always placed inside a folder with the samen name as the zipfile.

Is there a way to save the files to the root of the zip file?

Thanks in advance!

Worked Fine for Me

Index.php

<?php

$zip = new ZipArchive();

if (!$zip->open('zipfile.zip', ZipArchive::CREATE))
    exit("cannot open <$filename>\n");

$zip->addFromString('test.txt', 'tf is this?');
$zip->close();

Start Webserver

$ php -S localhost:8000

Output is zipfile.zip with test.txt at the root.

Folder Structure
 |--testProject |----index.php |----zipfile.zip 
zipfile.zip
|--zipfile.zip
|----text0.txt
|----text1.txt
|----text2.txt
|----text3.txt
|----text4.txt
|----text5.txt
|----text6.txt

Example w/ Multiple Files

 <?php $zip = new ZipArchive(); if (!$zip->open('zipfile.zip', ZipArchive::CREATE)) exit("cannot open <$filename>\\n"); for ($i=0; $i<7; $i++) $zip->addFromString("test$i.txt", 'tf is this?'); $zip->close(); 

Outputs

 |--zipfile.zip |----text0.txt |----text1.txt |----text2.txt |----text3.txt |----text4.txt |----text5.txt |----text6.txt 

Notes: This extension has no configuration directives defined in php.ini

Tested on PHP 5.5.15

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