You are here:Home » PHP » PHP Script to Compress Folder

PHP Script to Compress Folder

compress folder
Sometimes we need to compress entire folder including sub folders and files.To compress entire folder using ZipArchive() class you need to scan all folders and files.After assigning all files and folder in any variable you can easily add them to zip archive one by one.So here is the entire process to compress a folder containing sub-folders and files with PHP.
1.Choose path and output file name-Assign the relative path of folder which will be compressed in $folder variable and name of output folder in $zipvariable.
<?php
$folder="folder/";
$output="compressed.zip";
2.Create a ZipArchive object-Create an object say $zip of ZipArchive() class of PHP.
$zip = new ZipArchive();
3.Create a ZipArchive and open it-Create a new zip archive and open it.
if ($zip->open($output, ZIPARCHIVE::CREATE) !== TRUE) {
    die ("Unable to open Zip Archive ");
}
4.Read all files and folders-Read all files and folders of the directory and assign them into an array.
$all = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($folder));
5.Add files and folder to archive-Add each and every files and folders to archive.

foreach ($all as $f=>$value) {
	$zip->addFile(realpath($f), $f) or die ("ERROR: Unable to add file: $f");
}
6.Close archive-Close archive and free CPU resources.
$zip->close();
echo "Compressed Successfully";
?>
Here is the entire code to compress a folder containing sub-folders and files with PHP.
<?php
//file name:compress.php
//Title:How to compress a Folder containing Sub-Folders and Files with PHP
//Date:6-12-2012
$folder="path/";
$output="compressed.zip";
$zip = new ZipArchive();

if ($zip->open($output, ZIPARCHIVE::CREATE) !== TRUE) {
    die ("Unable to open Archirve");
}

$all= new RecursiveIteratorIterator(new RecursiveDirectoryIterator($folder));

foreach ($all as $f=>$value) {
	$zip->addFile(realpath($f), $f) or die ("ERROR: Unable to add file: $f");
}
$zip->close();
echo "Compressed Successfully";
?>

8 comments: