PHP如何打包下载ziparchive的使用
黑灯舞
10年前
之前在做一个有关文件操作的时候,遇到一个多文件下载的问题
//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 php 系统自带类,具体使用方法参照:http://cn2.php.net/manual/en/class.ziparchive.php $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; } }
//Sample Usage $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');
// php下载 function download($file_dir='web/uploadfile/', $file_name) { //检查文件是否存在 if (! file_exists ( $file_dir . $file_name )) { echo "文件找不到"; exit (); } else { //打开文件 $file = fopen ( $file_dir . $file_name, "r" ); //输入文件标签 Header ( "Content-type: application/octet-stream" ); Header ( "Accept-Ranges: bytes" ); Header ( "Accept-Length: " . filesize ( $file_dir . $file_name ) ); Header ( "Content-Disposition: attachment; filename=" . $file_name ); //输出文件内容 //读取文件内容并直接输出到浏览器 echo fread ( $file, filesize ( $file_dir . $file_name ) ); fclose ( $file ); exit (); } }