ZIP all files in directory and download generated .zip
Here is an example of how you can use PHP to create a ZIP archive of all files in a directory and then prompt the user to download the generated ZIP file:
Here is an example of how you can use PHP to create a ZIP archive of all files in a directory and then prompt the user to download the generated ZIP file:
Example of using PHP to create a ZIP archive of all files in a directory and then prompt the user to download the generated ZIP file
<?php
$dir = 'path/to/your/directory';
// Normalize directory path to prevent trailing slash issues
$dir = rtrim($dir, '/\\');
if (!is_dir($dir)) {
die('Directory not found.');
}
// Initialize archive object
$zip = new ZipArchive();
$zip_name = time() . ".zip"; // Zip name
if ($zip->open($zip_name, ZipArchive::CREATE) !== true) {
die('Failed to create zip file.');
}
// Create recursive directory iterator
/** @var SplFileInfo[] $files */
$files = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($dir), RecursiveIteratorIterator::LEAVES_ONLY);
foreach ($files as $name => $file) {
// Skip directories (they would be added automatically)
if (!$file->isDir()) {
// Get real and relative path for current file
$filePath = $file->getRealPath();
$relativePath = substr($filePath, strlen($dir) + 1);
// Add current file to archive
$zip->addFile($filePath, $relativePath);
}
}
// Zip archive will be created only after closing object
$zip->close();
//then prompt user to download the zip file
header('Content-Type: application/zip');
header('Content-Disposition: attachment; filename=' . $zip_name);
header('Content-Length: ' . filesize($zip_name));
readfile($zip_name);
//cleanup the zip file
unlink($zip_name);
exit;
?>
<div class="alert alert-info flex not-prose">![]()
<span class="hidden md:block">Watch a video course</span>Learn object oriented PHP</div>
This script will create a ZIP archive of all files in the specified directory, and then prompt the user to download the generated ZIP file. It is also cleaning up the zip file after download is complete. Please make sure to update the path to the directory you want to compress.