php code, Zip or Compress, each folder on my server, and name it the same as the folder

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:

  1. Set $directoryToZip to the path where the folders are located.
  2. Open the directory and loop through each folder.
  3. For each folder, create a new .zip file named after the folder.
  4. Use RecursiveDirectoryIterator and RecursiveIteratorIterator to add files recursively to the zip file.
  5. The script outputs the result for each folder.


Notes:

  • Permission: Ensure PHP has permission to read/write in the directory.
  • Error Handling: Check the output for any failed zips.
  • Performance: May take time for large directories.

Related Articles

- All From ChatGPT
PLG_GSPEECH_SPEECH_BLOCK_TITLE