Sunday, March 17, 2013

Create compressed zip file in PHP

How to create compressed/zip file using PHP?

This tutorial explains you the process of creating a zip file using PHP.
How to create captcha image

What is a compressed/zip file?

A zip file is a file that contains one or more compressed files in it. That means the size of the compressed file is lower than the original file(s) and can hold many files inside it. .zip file extension is use to identify compressed files.

There are number of compressed file formats. .zip, .rar, .7z and .gz are well known formats among them. compressed or archived files are useful when backup your data. Because if consumes less space and easily copy into removable media such as pen drive. Suppose that you have to develop a web application that sends some files to the client attached with a mail. In such case instead of attaching every file to the e-mail, you can create a compressed zip file and attach that file to the mail. Also when you are creating SQL backups, you can compressed those SQL files to save disk space and server bandwidth.

Demo: Online file compression tool - This tool can create zip archives online. What you have to do is simply upload files to compress or enter string to compress. It is free and easy.

Create ZIP compressed archive files using PHP?

PHP has in-built support for creating and reading compressed archived files. In latest PHP releases (PHP 5.3 or higher) Zip extension is included by default. But in previous releases you have to enable php_zip.dll in php.ini file. PHP use ZipArchive class to provide zip functionality. It is very easy to use. Using this extension you can create and read zip/compressed files. Also you can create zip files from string inputs or by using files. This tutorial explain everything that you need to know when creating compressed files in PHP.

How to check if zip extension is loaded?

You can make sure Zip extension is loaded as follows. To check whether an extension is loaded or not you can use extension_loaded function.

<?php

if(extension_loaded('zip')){
echo 'PHP zip extension is loaded';
}else{
echo 'PHP zip extension is not loaded';
}

?>

Also you can use phpinfo(INFO_MODULES) to check if the module is loaded. check zip extension is enabled.

1. How to create zip file using string input in PHP?

Following example code shows you to create a compressed archive file using string. That means you can make a zip file with a string input. In this exampl, entered text is convert to a text file and then it convert to a zip file. First of all check the demo program.

<?php
$zip = new ZipArchive();
$archive_name = "myZip.zip";

if ($zip->open($archive_name, ZIPARCHIVE::CREATE)!==TRUE) {
exit("Error while opening".$archive_name);
}

$zip->addFromString("testfile.txt", "You can create zip files from strings. here is the example tutorial.\n");
$zip->close();

echo 'File size = '.number_format((filesize($archive_name)/1024),2).' Kb';
?>

Above code will generate a zip file called 'myZip.zip' file in the directory which you run the PHP script. Make sure you have permission to create files in the folder. Also you can get the size of the created zip file.

Note: You can add more than one string to the zip file. You can add multiple strings as separate files in to the zip file. Checkout bellow example to add multiple files to the archive.

<?php
$zip = new ZipArchive();
$archive_name = "multiple.zip";

if ($zip->open($archive_name, ZIPARCHIVE::OVERWRITE)!==TRUE) {
exit("Error while opening $archive_name");
}

$zip->addFromString("first.txt", "This is the first string input.\n");
$zip->addFromString("second.txt", "This is the second string input.\n");
$zip->addFromString("third.txt", "This is the third string input. Likewise you can add multiple strings to create zip file\n");
$zip->close();

echo 'File size = '.number_format((filesize($archive_name)/1024),2).' Kb';
?>

2. How compress a file using PHP?


Above example explain you to create zip files using strings. This example shows you how to compress a file in your machine using PHP. Before you create zip archive make sure the file that is use to compress is exists in your machine. If zip file already exists you can overwrite it otherwise you can create a new zip file. before you proceed you have to specify what do you want to use. ZipArchive class has constant variables to define this.

use ZIPARCHIVE::CREATE to create a archive if it does not exist.
use ZIPARCHIVE::OVERWRITE to overwrite the file if it already exists.

<?php
$zip = new ZipArchive();
$archive_name = "myZip.zip";//name of the output zip file
$file_to_compress = "db.sql";//this is the file that you need to compress

if ($zip->open($archive_name, ZIPARCHIVE::OVERWRITE)!==TRUE) {
exit("Error while opening $archive_name");
}else{
if(file_exists($file_to_compress) && is_file($file_to_compress)){
$zip->addFile($file_to_compress,"db.sql");
$zip->close();
echo 'File size = '.number_format((filesize($archive_name)/1024),2).' Kb';
}else{
exit("File does not exists");
}
}
?>

Above PHP script will generate a compressed file of the db.sql. Use a large SQL backup file and check the zipped file size.

3. How to compress multiple files in PHP?

Suppose that you have to add more than one file to the zip file. In such situations you can use following code to create your zip archive. You have to check if the source file exist before you compress it. You can load files that you need to compress in to a php array. Study the following code and get the idea of compress multiple files.

<?php
$zip = new ZipArchive();
$archive_name = "multiple.zip";//name of the output zip file
$files_to_compress = array("database-backup.sql","cv.doc","index.php","access.log");//array of files that you need to compress

if ($zip->open($archive_name, ZIPARCHIVE::OVERWRITE)!==TRUE) {
exit("Error while opening $archive_name");
}else{
foreach($files_to_compress as $file){
if(file_exists($file) && is_file($file)){//check if file exist before it added to the zip file
$zip->addFile($file,$file);
}
}
$zip->close();
if(file_exists($archive_name) && is_file($archive_name)){
echo 'File size = '.number_format((filesize($archive_name)/1024),2).' Kb';
}else{
echo 'Unable to locate zip file';
}
}
?>

 

4. How to compress entire directory/folder PHP?

Now You have already know how to make zip files in php and compress more than one file in to a single archive. The next challenge is compress entire directory with all its contents. Following example shows you how to compress whole directory in PHP. This script is based on a recursive function. So it added all files in the given folder recursively. Also you can get the total compressed files in the archive. After you have compressed all files in the directory sometimes source files may be not useful furthermore. So you can delete all source files after make the zip file to gain more disk space. You can do it using following script.


<?php
/*
Copyright by Duminda Chamara
http://www.latestcode.net

Create Zip Archive in PHP
*/

function zip_entire_folder(&$zip_archive,$folder_path){
if(!(file_exists($folder_path) && is_dir($folder_path))){
return 0;
}
foreach(scandir($folder_path) as $file){
if(is_dir($folder_path.DIRECTORY_SEPARATOR.$file) && $file != ".." && $file != "."){
zip_entire_folder($zip_archive,$folder_path.DIRECTORY_SEPARATOR.$file);
}else{
if($file != ".." && $file != "."){
$file_name = $folder_path.DIRECTORY_SEPARATOR.$file;
$zip_archive->addFile($file_name,$file_name);
}
}
}
return true;
}

/*
Delete Source files after compression
*/

function delete_source_files($dir) {
foreach(glob($dir . '/*') as $file) {
if(is_dir($file)){
delete_source_files($file);
}else{
chmod($file,0750);
unlink($file);
}
}
rmdir($dir);
}
/*
Usage
*/

$zip_archive = new ZipArchive();
$archive_name = 'fckeditor.zip';//This is the output file name.
$folder_to_compress = 'fckeditor';// This is the folder that you need to compress.
$delete_source_files = true;//Delete source files after created the archive.

if ($zip_archive->open($archive_name, ZIPARCHIVE::OVERWRITE)!==TRUE) {
exit("Error while opening $filename");
}else{
zip_entire_folder($zip_archive,$folder_to_compress);
}
$no_of_zipped_files = $zip_archive->numFiles;$zip_archive->close();

if($delete_source_files){
delete_source_files($folder_to_compress);
}

if(file_exists($archive_name) && is_file($archive_name)){
echo 'File size = '.number_format((filesize($archive_name)/1024),2).'Kb<br/>Number of compressed files '.$no_of_zipped_files;
}else{
echo 'Unable to locate zip file';
}

?>

5. How to add comments to the zip/compressed archive in PHP?

Sometimes you may have seen some comments while opening a archive. These comments includes some useful information regarding the archive such as hash values, contact information, etc. You can Set a comment to the ZIP archive using PHP. See bellow example how to insert a comment to a zip archive using PHP.

<?php

$zip = new ZipArchive();
$archive_name = "archive-with-comment.zip";
$file_to_compress = "database-backup.sql";

if ($zip->open($archive_name, ZIPARCHIVE::OVERWRITE)!==TRUE) {
exit("Error while opening $archive_name");
}else{
if(file_exists($file_to_compress) && is_file($file_to_compress)){
$zip->addFile($file_to_compress,$file_to_compress);
$zip->setArchiveComment('You can type your comment here');
$zip->close();
echo 'File size = '.number_format((filesize($archive_name)/1024),2).' Kb';
}else{
exit("File does not exists");
}
}
?>

1 comments:

Martin said...

What would you recommend where the zip extension is not available? Is zlib a good option?