开放的编程资料库

当前位置:我爱分享网 > PHP教程 > 正文

使用 PHP 创建 Zip 文件

使用 PHP 创建 .ZIP 存档与在桌面上创建它们一样简单。 PHP 的 ZIP 类提供了您需要的所有功能!为了让您的过程更快一些,我编写了一个简单的 create_zip 函数供您在项目中使用。

PHP

/* creates a compressed 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) {
			$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_to_zip = array(
	'preload-images/1.jpg',
	'preload-images/2.jpg',
	'preload-images/5.jpg',
	'kwicks/ringo.gif',
	'rod.jpg',
	'reddit.gif'
);
//if true, good; if false, zip creation failed
$result = create_zip($files_to_zip,'my-archive.zip');

该函数接受一个文件数组、目标文件的名称,以及您是否希望在存在同名文件时覆盖目标文件。如果文件已创建,该函数返回 true,如果进程遇到任何问题,则返回 false。

此功能非常适合基于 Web 的文件管理器。谁知道呢,我可能只是将其提交给 Christoph 的 MooTools FileManager 项目。快乐的拉链!

未经允许不得转载:我爱分享网 » 使用 PHP 创建 Zip 文件

感觉很棒!可以赞赏支持我哟~

赞(0) 打赏