Invalid or uninitialized Zip object: The hidden scope trap
When debugging PHP issues involving ZipArchive, a common error message is Warning: ZipArchive::addFile() [function.ZipArchive-addFile]: Invalid or uninitialized Zip object. This specific warning, combined with the observation that single-file downloads work but multi-file selections fail, points immediately to a structural flaw in how the archive instance is being managed within your loop.
In the provided code snippet, the logic error lies in the placement of the $zip->close() call. The script opens the archive once for the entire request but closes it inside the foreach loop that iterates over every selected item.
foreach ($_POST['items'] as $path) {
// ... file existence check ...
$zip->addFile($filepath, $path . '.zip') or die("ERROR...");
$zip->close(); // <--- This is the problem
}
By calling $zip->close() on every iteration, you are finalizing and destroying the archive handle after adding just the first file. On the subsequent loop iterations, $zip no longer represents a valid, open instance of ZipArchive. It effectively becomes an uninitialized object for the purposes of that class's methods. When the code attempts to execute $zip->addFile() in the second or third iteration, PHP cannot operate on the closed resource, triggering the "uninitialized Zip object" warning and halting execution.
The fix is straightforward: move the closure logic outside the loop. The archive must remain open for the entire duration of the foreach operation so that it can accumulate all selected files into a single stream before being finalized.
if ($zip->open($zip_path, ZIPARCHIVE::CREATE | ZIPARCHIVE::OVERWRITE) !== TRUE) {
die ("An error occurred creating your ZIP file.");
}
foreach ($_POST['items'] as $path) {
$filepath = 'downloads/' . $path . '.zip';
if (file_exists($filepath)) {
// Ensure you are using the correct variable name here
$zip->addFile($filepath, $path);
} else {
die("File $filepath doesn't exist");
}
}
// Close only after all files have been added
$zip->close();
There is also a secondary logic error in the original snippet regarding variable consistency. The die() message inside the loop references $filename, but the code that populates the archive uses $filepath. If this were a production script, that typo would result in confusing error messages or silent failures depending on how PHP's error reporting is configured. Always ensure the variable used in the method call matches the one intended for validation.
Resource Management Best Practices
This specific bug highlights a broader principle of resource management in PHP: Do not treat streams or archive objects as disposable within a processing loop.
If you need to process thousands of files, closing and reopening the archive repeatedly would indeed be inefficient, but it requires careful handling. However, for standard batch operations like creating a download package, keeping the handle open is the correct approach. The ZipArchive class expects you to perform all additions before calling close(). Once closed, the internal file pointer resets, and subsequent attempts to write data will fail with the exact error seen in your logs.
Additionally, consider the implications of the addFile parameters. In the corrected example, the second argument passed to addFile should correspond to the intended name inside the archive. The original code passed $path . '.zip'. If $path already represents a filename relative to a specific directory, appending .zip again might create nested archives or duplicate extensions depending on how the frontend submits the data. It is often safer to sanitize the input string and rely on the original file extension rather than manually concatenating it, unless you are intentionally creating a nested zip structure.
Conclusion
The error "Invalid or uninitialized Zip object" in this context is not a mystery of the ZipArchive class itself, but a consequence of prematurely closing the resource handle. By ensuring the archive remains open until all files have been processed and then closing it exactly once at the end of the script, the warning disappears, and your multi-file download feature will function as intended.