1. 程式人生 > 實用技巧 >php壓縮Zip檔案和檔案打包下載

php壓縮Zip檔案和檔案打包下載

<?php

namespace app\util;
/**
 * 關於檔案壓縮和下載的類
 * @author  panzhide
 * @version 1.0
 */

class ZipDownload
{

    protected $file_path;


    /**
     * 建構函式
     * @param [string] $path [傳入檔案目錄]
     */
    public function __construct($path)
    {
        $this->file_path = $path; //要打包的根目錄
    }



    
/** * 入口呼叫函式 * @return [type] [以二進位制流的形式返回給瀏覽器下載到本地] */ public function index() { $zip = new \ZipArchive(); $end_dir = $this->file_path . date('Ymd', time()) . '.zip'; //定義打包後的包名 $dir = $this->file_path; if (!is_dir($dir)) { mkdir($dir
); } if ($zip->open($end_dir, \ZipArchive::CREATE) === TRUE) { ///ZipArchive::OVERWRITE 如果檔案存在則覆蓋 $this->addFileToZip($dir, $zip); //呼叫方法,對要打包的根目錄進行操作,並將ZipArchive的物件傳遞給方法 $zip->close(); } if (!file_exists($end_dir)) { exit("無法找到檔案"); }
return $end_dir; // header("Cache-Control: public"); // header("Content-Description: File Transfer"); // header("Content-Type: application/zip"); //zip格式的 // header('Content-disposition: attachment; filename=' . basename($end_dir)); //檔名 // header("Content-Transfer-Encoding: binary"); //告訴瀏覽器,這是二進位制檔案 // header('Content-Length:' . filesize($end_dir)); //告訴瀏覽器,檔案大小 // @readfile($end_dir); // $this->delDirAndFile($dir, true); //刪除目錄和檔案 // unlink($end_dir); ////刪除壓縮包 } /** * 檔案壓縮函式 需要開啟php zip擴充套件 * @param [string] $path [路徑] * @param [object] $zip [擴充套件ZipArchive類物件] */ protected function addFileToZip($path, $zip) { $handler = opendir($path); while (($filename = readdir($handler)) !== false) { if ($filename != "." && $filename != "..") { if (!is_dir($filename)) { $zip->addFile($path . "/" . $filename, $filename); //第二個引數避免將目錄打包,可以不加 } } } @closedir($path); } /** * 刪除檔案函式 * @param [string] $dir [檔案目錄] * @param boolean $delDir [是否刪除目錄] * @return [type] [description] */ protected function delDirAndFile($path, $delDir = true) { $handle = opendir($path); if ($handle) { while (false !== ($item = readdir($handle))) { if ($item != "." && $item != "..") { if (is_dir($path . '/' . $item)) { $this->delDirAndFile($path . '/' . $item, $delDir); } else { unlink($path . '/' . $item); } } } @closedir($handle); if ($delDir) { return rmdir($path); } } else { if (file_exists($path)) { return unlink($path); } else { return FALSE; } } } }