首頁  >  文章  >  後端開發  >  如何使用PHP ZipArchive建立zip檔並下載?

如何使用PHP ZipArchive建立zip檔並下載?

藏色散人
藏色散人原創
2019-02-28 13:19:593996瀏覽

在專案開發過程中,我們可能需要實作建立zip檔案並提供下載的功能。那這裡我們就可以使用ZipArchive類別來建立zip文件,然後進行下載。

如何使用PHP ZipArchive建立zip檔並下載?

我給你們舉個簡單的例子。有時候我們需要使用php程式碼建立zip歸檔文件,在zip檔案中加入一些照片、文件等,然後提供下載。這裡我們將建立一個非常簡單的方法createZip(),它將幫助建立zip歸檔檔案。使用這個方法,你可以簡單地傳遞數組的文件,文檔,圖片與路徑。

相關推薦:《【zip檔案類別庫】10個php zip檔案類別庫下載

下面我寫了一個非常簡單的index.php檔案範例,大家可以直接複製並在本地運行進行測試。

確保在index.php檔案有可用的圖片檔案:

1)demo1.jpg
2)demo2.jpg

程式碼範例如下:

 <?php


/* create a compressed zip file */
function createZip($files = array(), $destination = &#39;&#39;, $overwrite = false) {


    if(file_exists($destination) && !$overwrite) { return false; }


    $validFiles = [];
    if(is_array($files)) {
        foreach($files as $file) {
            if(file_exists($file)) {
                $validFiles[] = $file;
            }
        }
    }


    if(count($validFiles)) {
        $zip = new ZipArchive();
        if($zip->open($destination,$overwrite ? ZIPARCHIVE::OVERWRITE : ZIPARCHIVE::CREATE) !== true) {
            return false;
        }


        foreach($validFiles as $file) {
            $zip->addFile($file,$file);
        }


        $zip->close();
        return file_exists($destination);
    }else{
        return false;
    }
}


$fileName = &#39;my-archive.zip&#39;;
$files_to_zip = [&#39;demo1.jpg&#39;, &#39;demo2.jpg&#39;];
$result = createZip($files_to_zip, $fileName);


header("Content-Disposition: attachment; filename=\"".$fileName."\"");
header("Content-Length: ".filesize($fileName));
readfile($fileName);

這篇文章就是關於使用PHP ZipArchive建立zip文件並下載的方法介紹,希望對需要的朋友有幫助!

以上是如何使用PHP ZipArchive建立zip檔並下載?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn