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:

<?php
$dir = 'path/to/your/directory';

// Initialize archive object
$zip = new ZipArchive();
$zip_name = time() . ".zip"; // Zip name
$zip->open($zip_name, ZipArchive::CREATE);

// 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);

?>

Watch a course Learn object oriented PHP

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.