2017-09-20 48 views
2

我有一個非常奇怪的問題,當壓縮一個目錄,並嘗試使用codeigniter下載。Codeignter Zip目錄和下載

下面是代碼

$this->load->library('zip'); //Loading the zip library 
    $directory = $_SESSION['directory-download-path']; //Getting the directory from session 
    $name = basename($directory); //get the name of the folder 
    $name = str_replace(" ", "_", $name).".zip"; //create the zip name 
    unset($_SESSION['directory-download-path']); //removing it from session 
    $this->zip->read_dir($directory); //read the directory 
    $this->zip->download($name); //download the zip 

這是非常簡單的。下載發生問題。我得到的zip文件,但當我解壓縮它,我得到一個與.zip.cpgz文件,並繼續提取類似的文件。因此我認爲它已經損壞。你能幫我解釋爲什麼會發生這種情況。我有權限和目錄上的所有內容,因爲我正在執行其他操作。

編輯:

我經過一番更多的研究發現,添加第二個參數如下:

$this->zip->read_dir($directory, false); //read the directory 

但仍然沒有工作。 另一種解決方案只是行前加

ob_end_clean(); 

$this->zip->download($name); //download the zip

,但仍然沒有成功!

由於

回答

0

由於我沒有響應我外製成的函數笨該遞歸拉鍊的文件和文件夾,其是下面的:在笨控制器我在此

public function Zip($source, $destination) 
{ 
    if (!extension_loaded('zip') || !file_exists($source)) { 
     return false; 
    } 

    $zip = new ZipArchive(); 
    if (!$zip->open($destination, ZIPARCHIVE::CREATE)) { 
     return false; 
    } 

    $source = str_replace('\\', '/', realpath($source)); 

    if (is_dir($source) === true) 
    { 
     $files = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($source), RecursiveIteratorIterator::SELF_FIRST); 

     foreach ($files as $file) 
     { 
      $file = str_replace('\\', '/', $file); 

      if(in_array(substr($file, strrpos($file, '/')+1), array('.', '..', "Thumbs.db"))) 
       continue; 

      $file = realpath($file); 

      if (is_dir($file) === true) 
      { 
       $zip->addEmptyDir(str_replace($source . '/', '', $file . '/')); 
      } 
      else if (is_file($file) === true) 
      { 
       $zip->addFromString(str_replace($source . '/', '', $file), file_get_contents($file)); 
      } 
     } 
    } 
    else if (is_file($source) === true) 
    { 
     $zip->addFromString(basename($source), file_get_contents($source)); 
    } 

    return $zip->close(); 
} 

在此之後:

$this->projects->Zip($source, $destination); 
    header("Content-type: application/zip"); 
    header("Content-Disposition: attachment; filename=$name"); 
    header("Content-length: " . filesize($destination)); 
    header("Pragma: no-cache"); 
    header("Expires: 0"); 
    readfile($destination); 
    unlink($destination); 

當然$destination應該是一個臨時文件夾,在那裏你有權限777或等效,以便當文件發送到客戶端將被刪除。

希望這會有所幫助!