PHP 7 Script to ZIP All Files inside a Directory or Folder and Download it as ZIP or RAR File in Browser

Hey reader! Do you know one thing? Using this article, you can easily PHP 7 Script to ZIP All Files inside a Directory or Folder and Download it as ZIP or RAR File in Browser.

PHP 7 Script to ZIP All Files inside a Directory or Folder and Download it as ZIP or RAR File in Browser

PHP 7 Script to ZIP All Files inside a Directory or Folder and Download it as ZIP or RAR File in Browser

// Get real path for our folder
$rootPath = realpath('folder-to-zip');

// 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();

Final Words

We are confident that you will understand the PHP 7 Script to ZIP All Files inside a Directory or Folder and Download it as ZIP or RAR File in Browser article. Also if you have any information regarding this article please let us know in the comment box way comment.

Hi, I'm Selva a full-time Blogger, YouTuber, Affiliate Marketer, & founder of Coding Deekshi. Here, I post about programming to help developers.

Share on:

Leave a Comment