Created
December 12, 2022 11:24
-
-
Save alpenzoo/754167b6e1bff1fcfbb9fc6a638cfb6d to your computer and use it in GitHub Desktop.
creates a ZIP file and return it as a stream:
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function create_zip_stream($file_paths) | |
{ | |
// Create a new ZipArchive object | |
$zip = new ZipArchive(); | |
// Open a memory stream for the zip file | |
$zip_stream = fopen('php://memory', 'w+'); | |
$zip->open($zip_stream, ZipArchive::CREATE); | |
// Add the files to the zip | |
foreach ($file_paths as $file_path) { | |
$zip->addFile($file_path); | |
} | |
// Close the zip and return the stream | |
$zip->close(); | |
rewind($zip_stream); | |
return $zip_stream; | |
} | |
$file_paths = ['/path/to/file1.txt', '/path/to/file2.txt']; | |
// Create the zip stream | |
$zip_stream = create_zip_stream($file_paths); | |
// Set the HTTP headers | |
header('Content-Type: application/zip'); | |
header('Content-Disposition: attachment; filename="files.zip"'); | |
// Output the zip stream | |
fpassthru($zip_stream); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment