How To Create Zip File In PHP Using Custom Ziparchive Class Example?
Teams applying “How To Create Zip File In PHP Using Custom Ziparchive Class Example?” in a production project can use the operational overview to record implementation, review and debugging time, then compare that effort with tests and shipped functionality instead of treating activity as performance by itself.
Before copying the example into a live application, confirm version-specific behaviour with the PHP project and test it against the project’s actual database and runtime.
Hi guys,
Today i will explained how to create a zip file in custom ziparchiver class through. This example is so easy to use in php. This example to i am create a custom ziparchiver class in php
This tutorial to your folder to create a zip file in unique name to create. I am create a timezone_map folder and one dummy file. Then i am create a second folder in archive_files to dowload your create zip file.
So you are follow for my step by step.
So let's start to the example.
Index.php
<?php
// Include and initialize ZipArchive class
require_once 'ZipArchiver.class.php';
$zipper = new ZipArchiver;
// Path of the directory to be zipped
$dirPath = 'timezone_map';
// Path of output zip file
$zipPath = 'archive_files/archive-'.time().'.zip';
// Create zip archive
$zip = $zipper->zipDir($dirPath, $zipPath);
if($zip){
echo 'ZIP archive created successfully.';
}else{
echo 'Failed to create ZIP.';
}
?>
ZipArchiver.class.php
<?php
Class ZipArchiver {
/**
* Folder path that should be zipped.
*
* @return response()
*/
public static function zipDir($sourcePath, $outZipPath){
$pathInfo = pathinfo($sourcePath);
$parentPath = $pathInfo['dirname'];
$dirName = $pathInfo['basename'];
$z = new ZipArchive();
$z->open($outZipPath, ZipArchive::CREATE);
$z->addEmptyDir($dirName);
if($sourcePath == $dirName){
self::dirToZip($sourcePath, $z, 0);
}else{
self::dirToZip($sourcePath, $z, strlen("$parentPath/"));
}
$z->close();
return true;
}
/**
* Add files and sub-directories in a folder to zip file.
*
* @return response()
*/
private static function dirToZip($folder, &$zipFile, $exclusiveLength){
$handle = opendir($folder);
while(FALSE !== $f = readdir($handle)){
if($f != '.' && $f != '..' && $f != basename(__FILE__)){
$filePath = "$folder/$f";
$localPath = substr($filePath, $exclusiveLength);
if(is_file($filePath)){
$zipFile->addFile($filePath, $localPath);
}elseif(is_dir($filePath)){
$zipFile->addEmptyDir($localPath);
self::dirToZip($filePath, $zipFile, $exclusiveLength);
}
}
}
closedir($handle);
}
}
?>
Now you can check your own.
- How To Use Php Conditional Statement Example
- How to Check if String Contains Regex in PHP?
- PHP Array_column() Function Example
- PHP Generate List of Random Numbers Between 0 and 100 Example
- How to User Login with Facebook in PHP?
- How to Explode Every Character into Array Using PHP Example?
- PHP Form Validation Tutorial
- PHP Convert XML to JSON Example