How to Zip a Whole Folder Using PHP

How to zip a whole folder using PHP

Code updated 2015/04/22.

Zip a whole folder:

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

Zip a whole folder + delete all files except "important.txt":

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

// Initialize empty "delete list"
$filesToDelete = array();

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

// Add current file to "delete list"
// delete it later cause ZipArchive create archive only after calling close function and ZipArchive lock files until archive created)
if ($file->getFilename() != 'important.txt')
{
$filesToDelete[] = $filePath;
}
}
}

// Zip archive will be created only after closing object
$zip->close();

// Delete all files from "delete list"
foreach ($filesToDelete as $file)
{
unlink($file);
}

How to ZIP an entire folder in PHP, even the empty ones?

// Initialize archive object
$zip = new ZipArchive();
$zip->open($zipFilename, 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)
{
// Get real and relative path for current file
$filePath = $file->getRealPath();
$relativePath = substr($filePath, strlen($rootPath) + 1);

if (!$file->isDir())
{
// Add current file to archive
$zip->addFile($filePath, $relativePath);
}else {
if($relativePath !== false)
$zip->addEmptyDir($relativePath);
}
}

// Zip archive will be created only after closing object
$zip->close();

Hi. I modified the previous answer and now I get the zip file including the empty folders. I hope this helps.

ZIP all files in directory and download generated .zip

this will ensure a file with .php extension will not be added:

   foreach ($files as $file) {
if(!strstr($file,'.php')) $zip->addFile($file);
}

edit: here's the full code rewritten:

<?php

$zipname = 'adcs.zip';
$zip = new ZipArchive;
$zip->open($zipname, ZipArchive::CREATE);
if ($handle = opendir('.')) {
while (false !== ($entry = readdir($handle))) {
if ($entry != "." && $entry != ".." && !strstr($entry,'.php')) {
$zip->addFile($entry);
}
}
closedir($handle);
}

$zip->close();

header('Content-Type: application/zip');
header("Content-Disposition: attachment; filename='adcs.zip'");
header('Content-Length: ' . filesize($zipname));
header("Location: adcs.zip");

?>

ZIP all files in directory and download generated .zip

this will ensure a file with .php extension will not be added:

   foreach ($files as $file) {
if(!strstr($file,'.php')) $zip->addFile($file);
}

edit: here's the full code rewritten:

<?php

$zipname = 'adcs.zip';
$zip = new ZipArchive;
$zip->open($zipname, ZipArchive::CREATE);
if ($handle = opendir('.')) {
while (false !== ($entry = readdir($handle))) {
if ($entry != "." && $entry != ".." && !strstr($entry,'.php')) {
$zip->addFile($entry);
}
}
closedir($handle);
}

$zip->close();

header('Content-Type: application/zip');
header("Content-Disposition: attachment; filename='adcs.zip'");
header('Content-Length: ' . filesize($zipname));
header("Location: adcs.zip");

?>

How to [recursively] Zip a directory in PHP?

Here is a simple function that can compress any file or directory recursively, only needs the zip extension to be loaded.

function Zip($source, $destination)
{
if (!extension_loaded('zip') || !file_exists($source)) {
return false;
}

$zip = new ZipArchive();
if (!$zip->open($destination, ZIPARCHIVE::CREATE)) {
return false;
}

$source = str_replace('\\', '/', realpath($source));

if (is_dir($source) === true)
{
$files = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($source), RecursiveIteratorIterator::SELF_FIRST);

foreach ($files as $file)
{
$file = str_replace('\\', '/', $file);

// Ignore "." and ".." folders
if( in_array(substr($file, strrpos($file, '/')+1), array('.', '..')) )
continue;

$file = realpath($file);

if (is_dir($file) === true)
{
$zip->addEmptyDir(str_replace($source . '/', '', $file . '/'));
}
else if (is_file($file) === true)
{
$zip->addFromString(str_replace($source . '/', '', $file), file_get_contents($file));
}
}
}
else if (is_file($source) === true)
{
$zip->addFromString(basename($source), file_get_contents($source));
}

return $zip->close();
}

Call it like this:

Zip('/folder/to/compress/', './compressed.zip');

Compressing and extracting a Directory with all its files using PHP

First of all if you want to perform zipping and unzipping operations using php it is must to install php zip extension,as i am using Ubuntu as my OS and php7.0 on my server i installed it using this command.

sudo apt-get install php7.0-zip

For zipping parent directory and other sub directories along side with its files you can use this method given in approved answer.i have used it myself and its best to do so.

Transfer file using php cURL to other server.Now to unzip a folder in a new folder whichever you are trying to extract files in,first create that directory using this php code.

@mkdir(PATH.'/'.$TO.$NEW.'/'.$DIR_WITH_DIR_NAME,0777,true);

This will create the directory and give it all read/write permissions
now use this code to extract a directory

$zip = new ZipArchive;
if ($zip->open(PATH.'/'.$TO.$COMPRESSED.'/'.$FILE.'.zip') === TRUE) {

if(is_dir(PATH.'/'.$TO.$NEW.'/'.$DIR_WITH_DIR_NAME)){
$zip->extractTo(PATH.'/'.$TO.$NEW.'/'.$DIR_WITH_DIR_NAME);
}
$zip->close();
echo 'extracted';
} else {
echo 'error in file extracting';
}

That's it all of the files will be extracted into newly created directory enjoy happy coding.



Related Topics



Leave a reply



Submit