Create A Zip File And Uncompress Or Unzip A Zip File Using PHP And ZipArchive
Are you curious about PHP capability of creating a zip file and extracting/unzip/unzompress a zip file? Actually, there are some ways to do it such as using shell script or using a PHP Class Library. In this article, we will use ZipArchive which is one of PHP class libraries that handles zip compression. Here is how to use it and the sample code.
Source Code
[php]<?
//By : Isusx Programming Corner
//URL : http://isusx.com
//Extracting a zip file
$zip = new ZipArchive;
//Open a zip file, just set it to a zip file that you want to extract
//It can be a relative path or absolute path
$res = $zip->open(’sample.zip’);
if ($res === true) {
//Zip file is exist and readable
//Start extracting the zip file
//Just specify the target location
$zip->extractTo(’path/somwhere’);
$zip->close();
//Extract success
}else{
//Zip file is not readable or not exist
echo ‘Error: ‘.$res;
}
//Creating or Overwriting a zip file
$zip = new ZipArchive;
//Specify a new zip file name and the mode
//To create a new zip file use ZipArchive::CREATE
//To overwrite an existing zip file use ZIPARCHIVE::OVERWRITE
$res = $zip->open(’sample.zip’, ZipArchive::CREATE);
if ($res === true) {
//Zip file is created
//Start adding files
//To add a string value to the zip file
//The first parameter is the file name for the zipped file
//The second parameter is the string
$zip->addFromString(’file1.txt’, ’some text or content’);
//To add a file to the zip file
//The first parameter is the file name that will be zipped
//The second parameter is the file name for the zipped file
$zip->addFile(’sample.xls’, ‘filenameinzip.xls’);
$zip->close();
//Zip file created
} else {
//Zip file is not readable or not exist
echo ‘Error: ‘.$res;
}
?>[/php]
Copyright Note
This script is free to use and can be modified as your wish.
Related Links
About Zip
PHP: Zip Manual




