To generate zip files in php, we only need to use a php zip compression ZipArchive function. The following editor will summarize two implementations for you. One is to use ZipArchive to generate zip, and the other is to compress all files in the folder.
Note:
ZipArchive to compress files. This is an extension class of php. This extension has been supported since php5.2 version. If you get an error when using it, check whether the semicolon in front of extension=php_zip.dll in php.ini has been removed, and then try again. Restart Apache to use this library.
Example 1
Generate zip file
The code is as follows |
Copy code |
代码如下 |
复制代码 |
/* 生成zip 压缩文件 */
function create_zip($files = array(),$destination = '',$overwrite = false) {
//if the zip file already exists and overwrite is false, return false
if(file_exists($destination) && !$overwrite) { return false; }
//vars
$valid_files = array();
//if files were passed in...
if(is_array($files)) {
//cycle through each file
foreach($files as $file) {
//make sure the file exists
if(file_exists($file)) {
$valid_files[] = $file;
}
}
}
//if we have good files...
if(count($valid_files)) {
//create the archive
$zip = new ZipArchive();
if($zip->open($destination,$overwrite ? ZIPARCHIVE::OVERWRITE : ZIPARCHIVE::CREATE) !== true) {
return false;
}
//add the files
foreach($valid_files as $file) {
$file_info_arr= pathinfo($file);
$zip->addFile($file,$file_info_arr['basename']);//去掉层级目录
}
//debug
//echo 'The zip archive contains ',$zip->numFiles,' files with a status of ',$zip->status;
//close the zip -- done!
$zip->close();
//check to make sure the file exists
return file_exists($destination);
}
else
{
return false;
}
}
define('ROOTPATH',dirname ( __FILE__ )); //网站路径
$files_to_zip = array(
ROOTPATH.DIRECTORY_SEPARATOR.'PHP+jQuery+Cookbook.pdf',
ROOTPATH.DIRECTORY_SEPARATOR.'TurboListerZeroTemplate.csv'
);
//if true, good; if false, zip creation failed
$filename='my-archive.zip';
$result = create_zip($files_to_zip,$filename);
|
/* Generate zip file */
function create_zip($files = array(),$destination = '',$overwrite = false) {
//if the zip file already exists and overwrite is false, return false
If(file_exists($destination) && !$overwrite) { return false; }
//vars
$valid_files = array();
//if files were passed in...
If(is_array($files)) {
//cycle through each file
foreach($files as $file) {
//make sure the file exists
if(file_exists($file)) {
$valid_files[] = $file;
}
//if we have good files...
If(count($valid_files)) {
//create the archive
$zip = new ZipArchive();
If($zip->open($destination,$overwrite ? ZIPARCHIVE::OVERWRITE : ZIPARCHIVE::CREATE) !== true) {
return false;
//add the files
foreach($valid_files as $file) {
$file_info_arr= pathinfo($file);
$zip->addFile($file,$file_info_arr['basename']);//Remove the hierarchical directory
//debug
//echo 'The zip archive contains ',$zip->numFiles,' files with a status of ',$zip->status;
//close the zip -- done!
$zip->close();
//check to make sure the file exists
return file_exists($destination);
}
else
{
return false;
}
}
define('ROOTPATH',dirname ( __FILE__ )); //Website path
$files_to_zip = array(
ROOTPATH.DIRECTORY_SEPARATOR.'PHP+jQuery+Cookbook.pdf',
ROOTPATH.DIRECTORY_SEPARATOR.'TurboListerZeroTemplate.csv'
);
//if true, good; if false, zip creation failed
$filename='my-archive.zip';
$result = create_zip($files_to_zip,$filename);
|
Example 2
Compress all files under the folder
The code is as follows
代码如下 |
复制代码 |
/*
php zip压缩文件夹下面的所有文件
*/
class HZip
{
/**
* 添加文件和子目录的文件到zip文件
* @param string $folder
* @param ZipArchive $zipFile
* @param int $exclusiveLength Number of text to be exclusived from the file path.
*/
private static function folderToZip($folder, &$zipFile, $exclusiveLength) {
$handle = opendir($folder);
while (false !== $f = readdir($handle)) {
if ($f != '.' && $f != '..') {
$filePath = "$folder/$f";
// Remove prefix from file path before add to zip.
$localPath = substr($filePath, $exclusiveLength);
if (is_file($filePath)) {
$zipFile->addFile($filePath, $localPath);
} elseif (is_dir($filePath)) {
// 添加子文件夹
$zipFile->addEmptyDir($localPath);
self::folderToZip($filePath, $zipFile, $exclusiveLength);
}
}
}
closedir($handle);
}
/**
* Zip a folder (include itself).
* Usage:
* HZip::zipDir('/path/to/sourceDir', '/path/to/out.zip');
*
* @param string $sourcePath Path of directory to be zip.
* @param string $outZipPath Path of output zip file.
*/
public static function zipDir($sourcePath, $outZipPath)
{
$pathInfo = pathInfo($sourcePath);
$parentPath = $pathInfo['dirname'];
$dirName = $pathInfo['basename'];
$sourcePath=$parentPath.'/'.$dirName;//防止传递'folder' 文件夹产生bug
$z = new ZipArchive();
$z->open($outZipPath, ZIPARCHIVE::CREATE);//建立zip文件
$z->addEmptyDir($dirName);//建立文件夹
self::folderToZip($sourcePath, $z, strlen("$parentPath/"));
$z->close();
}
}
//使用方法
HZip::zipDir('yourlife', 'yourlife.zip');
?>
|
|
Copy code
/*
All files under the php zip compressed folder
*/
class HZip
{
/**
* Add files and subdirectories to zip file
* @param string $folder
* @param ZipArchive $zipFile
* @param int $exclusiveLength Number of text to be exclusive from the file path.
*/
private static function folderToZip($folder, &$zipFile, $exclusiveLength) {
$handle = opendir($folder);
While (false !== $f = readdir($handle)) {
If ($f != '.' && $f != '..') {
$filePath = "$folder/$f";
// Remove prefix from file path before add to zip.
$localPath = substr($filePath, $exclusiveLength);
If (is_file($filePath)) {
$zipFile->addFile($filePath, $localPath);
} elseif (is_dir($filePath)) {
// Add subfolder
$zipFile->addEmptyDir($localPath);
self::folderToZip($filePath, $zipFile, $exclusiveLength);
}
}
}
closedir($handle);
}
/**
* Zip a folder (include itself).
* Usage:
* HZip::zipDir('/path/to/sourceDir', '/path/to/out.zip');
*
* @param string $sourcePath Path of directory to be zip.
* @param string $outZipPath Path of output zip file.
*/
public static function zipDir($sourcePath, $outZipPath) |
{
$pathInfo = pathInfo($sourcePath);
|
$parentPath = $pathInfo['dirname'];
$dirName = $pathInfo['basename'];
$sourcePath=$parentPath.'/'.$dirName;//Prevent bugs from passing the 'folder' folder
$z = new ZipArchive();
$z->open($outZipPath, ZIPARCHIVE::CREATE);//Create zip file
$z->addEmptyDir($dirName);//Create a folder
Self::folderToZip($sourcePath, $z, strlen("$parentPath/"));
$z->close();
}
}
//How to use
HZip::zipDir('yourlife', 'yourlife.zip');
?>
/******** ziparchive optional parameter *******/
/*
1.ZipArchive::addEmptyDir
Add a new file directory
2.ZipArchive::addFile
Add files to the specified zip archive.
3.ZipArchive::addFromString
The content of the added files will be added at the same time
4.ZipArchive::close
Close ziparchive
5.ZipArchive::extractTo
Extract the compressed package
6.ZipArchive::open
Open a zip archive
7.ZipArchive::getStatusString
Returns the status content during compression, including error information, compression information, etc.
8.ZipArchive::deleteIndex
Delete a certain file in the compressed package, such as: deleteIndex(0) deletes the first file
9.ZipArchive::deleteName
Delete a certain file name in the compressed package and also delete the file.
......
*/
http://www.bkjia.com/PHPjc/632895.htmlwww.bkjia.comtruehttp: //www.bkjia.com/PHPjc/632895.htmlTechArticleTo generate zip files in php, we only need to use a php zip compression ZipArchive function. The following editor will give Let’s summarize the two implementations. One is to use ZipArchive to generate zip, and the other is to compress...