PHP代码示例:一键打包压缩目录文件
在PHP中,可以使用ZipArchive类来实现一键打包压缩目录文件的功能。以下是一个简单的示例代码: ```php <?php $zip = new ZipArchive(); if ($zip->open('example.zip', ZipArchive::CREATE) === TRUE) { $files = array('file1.txt', 'file2.txt'); // 需要压缩的文件列表 foreach ($files as $file) { $zip->addFile($file); } $zip->close(); echo '文件压缩成功!'; } else { echo '文件压缩失败!'; } ?> ``` 这段代码首先创建了一个ZipArchive对象,然后打开一个名为"example.zip"的压缩文件。接着,定义了一个包含需要压缩的文件名的数组,并使用addFile()方法将它们添加到压缩文件中。最后,关闭压缩文件并输出提示信息。
新建一个PHP文件,保存以下代码,放到需要打包的文件夹内,浏览器访问文件即可。
1 | <?php $button = $_POST [ 'button' ]; if ( $button == "开始打包" ){ $zip =newZipArchive(); $filename = "./" . date ( "Y-m-d" ). "_" .md5(time()). "_zy.zip" ; if ( $zip ->open( $filename ,ZIPARCHIVE::CREATE)!==TRUE){ exit ( "无法创建<$filename>n" );} $files =listdir(); foreach ( $filesas $path ){ $zip ->addFile( $path , str_replace ( "./" , "" , str_replace ( "" , "/" , $path )));} echo "压缩完成,共压缩了:" . $zip ->numFiles. "个文件n" ; $zip ->close();}Functionlistdir( $start_dir = '.' ){ $files = array (); if ( is_dir ( $start_dir )){ $fh =opendir( $start_dir ); while (( $file =readdir( $fh ))!==false){ if ( strcmp ( $file , '.' )==0|| strcmp ( $file , '..' )==0) continue ; $filepath = $start_dir . '/' . $file ; if ( is_dir ( $filepath )) $files = array_merge ( $files ,listdir( $filepath ));elsearray_push( $files , $filepath );} closedir ( $fh );} else { $files =false;} return $files ;}?><!DOCTYPEHTMLPUBLIC "-//W3C//DTDHTML4.0Transitional//EN" ><html><head><title>打包工具</title><metahttp-equiv= "Content-Type" content= "text/html;charset=gb2312" ></head><body><formname= "form1" method= "post" action= "" ><hrsize= "1" ><P><inputtype= "submit" name= "button" value= "开始打包" /></P></form></body></html> |