Skip to content

Instantly share code, notes, and snippets.

@szepeviktor
Last active May 8, 2025 06:04
Show Gist options
  • Save szepeviktor/d93146a4aa49ab6db740121daada0b36 to your computer and use it in GitHub Desktop.
Save szepeviktor/d93146a4aa49ab6db740121daada0b36 to your computer and use it in GitHub Desktop.
Archive WordPress uploads in a ZIP file on the server
<?php
function addDirToZip(string $dir, ZipArchive $zipFile, string $basePath = '')
{
$files = scandir($dir);
// Remove '.' and '..'
unset($files[0], $files[1]);
foreach ($files as $file) {
$filePath = $dir . $file;
$relativePath = $basePath . $file;
if (is_dir($filePath)) {
$zipFile->addEmptyDir($relativePath . '/');
addDirToZip($filePath . '/', $zipFile, $relativePath . '/');
} else {
$zipFile->addFile($filePath, $relativePath);
}
}
}
$sourceDir = 'wp-content/uploads/';
$zipFileName = 'uploads.zip';
$zip = new ZipArchive();
if ($zip->open($zipFileName, ZipArchive::CREATE) !== true) {
exit("Cannot open '$zipFileName'>\n");
}
addDirToZip($sourceDir, $zip);
$zip->close();
echo "ZIP file '$zipFileName' created successfully!\n";
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment