Search code examples
phpwindowsphp-ziparchive

PHP ZipArchive is not adding any files (Windows)


I'm failing to put even a single file into a new zip archive.

makeZipTest.php:

<?php

$destination = __DIR__.'/makeZipTest.zip';
$fileToZip = __DIR__.'/hello.txt';

$zip = new ZipArchive();
if (true !== $zip->open($destination, ZIPARCHIVE::OVERWRITE)) {
    die("Problem opening zip $destination");
}
if (!$zip->addFile($fileToZip)) {
    die("Could not add file $fileToZip");
}
echo "numfiles: " . $zip->numFiles . "\n";
echo "status: " . $zip->status . "\n";
$zip->close();

The zip gets created, but is empty. Yet no errors are triggered.

What is going wrong?


Solution

  • It seems on some configuration, PHP fails to get the localname properly when adding files to a zip archive and this information must be supplied manually. It is therefore possible that using the second parameter of addFile() might solve this issue.

    ZipArchive::addFile

    Parameters

    • filename
      The path to the file to add.
    • localname
      If supplied, this is the local name inside the ZIP archive that will override the filename.

    PHP documentation: ZipArchive::addFile

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

    You may have to adapt the code to get the right tree structure since basename() will remove everything from the path apart from the filename.