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

*/
相關文章
相關標籤/搜索