Compress/Archive Folder Using PHP Script

compress/archive folder using php script

Here is an example:

<?php

// Adding files to a .zip file, no zip file exists it creates a new ZIP file

// increase script timeout value
ini_set('max_execution_time', 5000);

// create object
$zip = new ZipArchive();

// open archive
if ($zip->open('my-archive.zip', ZIPARCHIVE::CREATE) !== TRUE) {
die ("Could not open archive");
}

// initialize an iterator
// pass it the directory to be processed
$iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator("themes/"));

// iterate over the directory
// add each file found to the archive
foreach ($iterator as $key=>$value) {
$zip->addFile(realpath($key), $key) or die ("ERROR: Could not add file: $key");
}

// close and save archive
$zip->close();
echo "Archive created successfully.";
?>

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

PHP compress files into zip

Just to demonstrate use of the undocumented addGlob() method of the zipArchive class:

$zipFile = dirname(__FILE__)."/myMP3s.zip";
$zipArchive = new ZipArchive();

if (!$zipArchive->open($zipFile, ZIPARCHIVE::OVERWRITE))
die("Failed to create archive\n");

$zipArchive->addGlob(dirname(__FILE__)."/*.mp3");
if (!$zipArchive->status == ZIPARCHIVE::ER_OK)
echo "Failed to write local files to zip\n";

$zipArchive->close();

How to create a zip file using PHP

$zip = new ZipArchive();

$DelFilePath="first.zip";

if(file_exists($_SERVER['DOCUMENT_ROOT']."/TEST/".$DelFilePath)) {

unlink ($_SERVER['DOCUMENT_ROOT']."/TEST/".$DelFilePath);

}
if ($zip->open($_SERVER['DOCUMENT_ROOT']."/TEST/".$DelFilePath, ZIPARCHIVE::CREATE) != TRUE) {
die ("Could not open archive");
}
$zip->addFile("file_path","file_name");

// close and save archive

$zip->close();

Here TEST is your project folder name.

You can define path as you want.

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