PHP在线压缩zip的函数代码

发布时间:2019-11-07编辑:脚本学堂
分享一个php在线压缩zip文件的函数,实现在线创建zip压缩包,有需要的朋友参考下。

例子,php实现zip文件的在线压缩。
 

复制代码 代码示例:
<?php
/* PHP创建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) {
$zip->addFile($file,$file);
}
//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;
}
}
/***** 应用实例 ***/
$files=array('1.php', 'mail.php', 'readme.txt');
create_zip($files, 'myzipfile.zip', true);
?>