PHP ZipArchive 压缩文件函数实现与使用示例
相关代码实现如下:
/* 创建一个压缩的 zip 文件 */
function create_zip($files = array(),$destination = '',$overwrite = false) {
//如果 zip 文件已存在且 overwrite 为 false,则返回 false
if(file_exists($destination) && !$overwrite) { return false; }
//变量初始化
$valid_files = array();
//如果有传入文件列表...
if(is_array($files)) {
//遍历每个文件
foreach($files as $file) {
//确保文件存在
if(file_exists($file)) {
$valid_files[] = $file;
}
}
}
//如果我们有有效的文件...
if(count($valid_files)) {
//创建归档
$zip = new ZipArchive();
if($zip->open($destination,$overwrite ? ZIPARCHIVE::OVERWRITE : ZIPARCHIVE::CREATE) !== true) {
return false;
}
//添加文件
foreach($valid_files as $file) {
$zip->addFile($file,$file);
}
//调试信息
//echo 'The zip archive contains ',$zip->numFiles,' files with a status of ',$zip->status;
//关闭 zip -- 完成!
$zip->close();
//检查文件是否存在
return file_exists($destination);
}
else
{
return false;
}
}
/***** 示例用法 ***/
$files=array('file1.jpg', 'file2.jpg', 'file3.gif');
create_zip($files, 'myzipfile.zip', true);
PHP Zip 文件在线解压缩的函数代码