What are some efficient ways to download multiple files at once in PHP, such as combining them into a zip file for easier access?

When needing to download multiple files at once in PHP, a common and efficient approach is to combine them into a zip file for easier access. This can be achieved by using the ZipArchive class in PHP to create a zip archive, add the files to it, and then offer the zip file for download to the user.

<?php

// Array of file paths to be zipped
$files = ['file1.txt', 'file2.jpg', 'file3.pdf'];

// Create a new ZipArchive object
$zip = new ZipArchive();

// Define the name of the zip file
$zipName = 'downloaded_files.zip';

// Open the zip file for writing
if ($zip->open($zipName, ZipArchive::CREATE) === TRUE) {
    // Add files to the zip archive
    foreach ($files as $file) {
        $zip->addFile($file);
    }
    // Close the zip file
    $zip->close();
    
    // Offer the zip file for download
    header('Content-Type: application/zip');
    header('Content-Disposition: attachment; filename="' . $zipName . '"');
    readfile($zipName);
    
    // Delete the zip file after download
    unlink($zipName);
} else {
    echo 'Failed to create zip file';
}

?>