Skip to content

Instantly share code, notes, and snippets.

@manishjaingit
Created July 8, 2017 13:35
Show Gist options
  • Save manishjaingit/7ede400a692945a6ce08b0a67b3f5aa4 to your computer and use it in GitHub Desktop.
Save manishjaingit/7ede400a692945a6ce08b0a67b3f5aa4 to your computer and use it in GitHub Desktop.
create zip of directory
<?php
// Get real path for our folder
$rootPath = realpath('folder_name');
// Initialize archive object
$zip = new ZipArchive();
$zip->open('filebkp.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();
?>
@manishjaingit
Copy link
Author

manishjaingit commented Jun 18, 2020

<?php
// Get real path for our folder
ini_set('max_execution_time',0);
$rootPath = realpath('application');

// Initialize archive object
$zip = new ZipArchive();
$zip->open('application.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