user2828677 user2828677 - 1 month ago 11
PHP Question

ZipArchive::addEmptyDir creates an empty file in .zip file

When i create an .zip archive with bellow code i get an strange empty file. It's ok when i add one file without creating directory. I can open archive, unpack it without errors. I am using WinRar 5.10 (in WinRar 5.0 and lower, 7zip, WinZip there is no problem).

$zip = new ZipArchive();
$filename = "test112.zip";

if ($zip->open($filename, ZipArchive::CREATE)!==TRUE) {
exit("cannot open <$filename>\n");
}
$zip->addEmptyDir('test');
$zip->addFile("apache_pb2.png", 'test/test.png');
$zip->close();


PrintScreen: CLICK

Any idea what's wrong?

Answer

It is likely that by running the addEmptyDir function and then running an addFile function into the same directory, you are actually creating two instances of test in the eyes of some Unzip programs. Generally this won't be an issue, but if you wish to avoid this for your version of WinRAR you should modify your code to the following:

$zip = new ZipArchive();
$filename = "test112.zip";

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

//$zip->addEmptyDir('test'); // Only necessary for directories that will REMAIN empty
$zip->addFile("apache_pb2.png", 'test/test.png');
$zip->close();