Created
February 17, 2023 06:19
-
-
Save javdome/bcfcfe80e5809e014bd6a3ce6afe1710 to your computer and use it in GitHub Desktop.
Zip the content of a folder in PHP
This file contains 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
<?php | |
// Get real path for our folder | |
$rootPath = realpath('./folderToZip'); | |
// Initialize archive object | |
$zip = new ZipArchive(); | |
$zip->open('file.zip', ZipArchive::CREATE | ZipArchive::OVERWRITE); | |
// Create recursive directory iterator | |
/** @var SplFileInfo[] $files */ | |
$files = new RecursiveIteratorIterator( | |
new RecursiveDirectoryIterator($rootPath), | |
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($rootPath) + 1); | |
// Add current file to archive | |
$zip->addFile($filePath, $relativePath); | |
} | |
} | |
// Zip archive will be created only after closing object | |
$zip->close(); | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment