PHP 壓縮檔成zip的函數
<?php<br />/* @creates a compressed zip file 將多個檔案壓縮成一個zip檔案的函數<br />*@$files 數群組類型 執行個體array("1.jpg","2.jpg");<br />*@destination 目標檔案的路徑 如"c:/androidyue.zip"<br />*@$overwrite 是否為覆蓋與目標檔案相同的檔案<br />*@Recorded By Androidyue<br />*@Blog:http://thinkblog.sinaapp.com<br /> */<br />function create_zip($files = array(),$destination = '',$overwrite = false) {<br />//if the zip file already exists and overwrite is false, return false<br />//如果zip檔案已經存在並且設定為不重寫返回false<br />if(file_exists($destination) && !$overwrite) { return false; }<br />//vars<br />$valid_files = array();<br />//if files were passed in...<br />//擷取到真實有效檔案名稱<br />if(is_array($files)) {<br />//cycle through each file<br />foreach($files as $file) {<br />//make sure the file exists<br />if(file_exists($file)) {<br />$valid_files[] = $file;<br />}<br />}<br />}<br />//if we have good files...<br />//如果存在真實有效檔案<br />if(count($valid_files)) {<br />//create the archive<br />$zip = new ZipArchive();<br />//開啟檔案 如果檔案已經存在則覆蓋,如果沒有則建立<br />if($zip->open($destination,$overwrite ? ZIPARCHIVE::OVERWRITE : ZIPARCHIVE::CREATE) !== true) {<br />return false;<br />}<br />//add the files<br />//向壓縮檔中添加檔案<br />foreach($valid_files as $file) {<br />$zip->addFile($file,$file);<br />}<br />//debug<br />//echo 'The zip archive contains ',$zip->numFiles,' files with a status of ',$zip->status;<br />//close the zip -- done!<br />//關閉檔案<br />$zip->close();<br />//check to make sure the file exists<br />//檢測檔案是否存在<br />return file_exists($destination);<br />}else{<br />//如果沒有真實有效檔案返回false<br />return false;<br />}<br />}<br />/****<br />//測試函數<br />$files=array('temp.php','test.php');<br />create_zip($files, 'myzipfile.zip', true);<br />****/<br />?>
摘自http://thinkblog.sinaapp.com 開放原始碼