1. 程式人生 > >PHP 多檔案打包下載 zip

PHP 多檔案打包下載 zip

<?php
$zipname = './photo.zip';

//伺服器根目錄下有資料夾public,其中包含三個檔案img1.jpg, img2.jpg, img3.jpg,將這三個檔案打包下載,並重設下載的目錄結構及檔名 file1/newimg1.jpg, file1/newimg2.jpg, file2/newimg.jpg
$fileArr[0] = array('file_path' => './public/img1.jpg', 'down_path' => 'file1/newimg1.jpg');
$fileArr[1] = array('file_path' => './public/img2.jpg', 'down_path' => 'file1/newimg2.jpg');
$fileArr[2] = array('file_path' => './public/img3.jpg', 'down_path' => 'file2/newimg.jpg'); //要使用該類,需要先啟用 extension=php_zip.dll $zip = new \ZipArchive (); $res = $zip->open ( $zipname, \ZipArchive::CREATE ); if ($res === TRUE) { foreach ( $fileArr as $file ) { //這裡將伺服器上的檔案新增到下載內容中,並重新賦值下載zip檔案內該檔案的路徑
$zip->addFile ( $file ['file_path'], $file ['down_path'] ); } } $zip->close (); header ( "Content-Type: application/zip" ); header ( "Content-Transfer-Encoding: Binary" ); header ( "Content-Length: " . filesize ( $zipname ) ); header ( "Content-Disposition: attachment; filename=\"" . basename
( $zipname ) . "\"" ); readfile ( $zipname ); //如不刪除,則在伺服器上會有 $zipname 這個zip檔案 @unlink ( $zipname ); /* 下載後的 photo.zip 壓縮包內包含兩個資料夾 file1,file2。file1內包含檔案為 newimg1.jpg,newimg2.jpg ,file2內包含檔案為 newimg.jpg photo.zip -- file1 -- newimg1.jpg -- newimg2.jpg -- file2 -- newimg.jpg */