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
How to Iterate Through Dom Elements in PHP
Move an Array Element to a New Index in PHP
Root Path Doesn't Work with PHP Include
How to Extract or Uncompress Gzip File Using PHP
How to Send Email from Local Wamp Server Using PHP
Which Is the Best Character Encoding for Japanese Language for Db, PHP, and HTML Display
Prevent Session Expired in PHP Session for Inactive User
PHP Password_Hash and Password_Verify Issues No Match
Fetching One Row Only with MySQLi
How to Get the External Ip of My Server Using PHP
How to Connect to Database on Another Server
Best Way to Parse an Invalid HTML in PHP
Return One Value from Database with MySQL PHP Pdo
PHP Spl_Autoload_Register VS _Autoload
PHP - Implement Logging Mechanism to File in Several Classes