Here's a PHP script that zips each folder in a specified directory and names the zip file after the folder:
<?php
// Set the directory you want to zip
$directoryToZip = "/path/to/your/folders";
// Open the directory
if ($handle = opendir($directoryToZip)) {
// Loop through the directory
while (($folder = readdir($handle)) !== false) {
// Skip the current and parent directory pointers
if ($folder === '.' || $folder === '..') continue;
// Only zip directories
$folderPath = $directoryToZip . DIRECTORY_SEPARATOR . $folder;
if (is_dir($folderPath)) {
// Define the zip file path and name it after the folder
$zipFile = $directoryToZip . DIRECTORY_SEPARATOR . $folder . ".zip";
$zip = new ZipArchive();
// Open a new zip file to add the contents
if ($zip->open($zipFile, ZipArchive::CREATE | ZipArchive::OVERWRITE) === true) {
// Function to recursively add files to zip
$files = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($folderPath), RecursiveIteratorIterator::LEAVES_ONLY);
foreach ($files as $name => $file) {
if (!$file->isDir()) {
$filePath = $file->getRealPath();
$relativePath = substr($filePath, strlen($directoryToZip) + 1);
$zip->addFile($filePath, $relativePath);
}
}
$zip->close();
echo "Folder '$folder' compressed successfully.<br>";
} else {
echo "Failed to create zip for folder '$folder'.<br>";
}
}
}
closedir($handle);
} else {
echo "Could not open directory.";
}
Explanation:
Notes: