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

*/

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM