2017-10-06 52 views
-3

我的網站上有一個圖片文件夾。當我加載我的頁面時,應該開始自動下載文件夾作爲Zip-File。如何以Zip-File的形式下載文件夾?

$dir = 'gallery/1/'; 
$zip_file = 'file.zip'; 

// Get real path for our folder 
$rootPath = realpath($dir); 

// Initialize archive object 
$zip = new ZipArchive(); 
$zip->open($zip_file, ZipArchive::CREATE | ZipArchive::OVERWRITE); 

// Create recursive directory iterator 
/** @var SplFileInfo[] $files */ 
$files = new RecursiveIteratorIterator(
    new RecursiveDirectoryIterator($rootPath), 
    RecursiveIteratorIterator::LEAVES_ONLY 
); 

foreach ($files as $name => $file) 
{ 
    // Skip directories (they would be added automatically) 
    if (!$file->isDir()) 
    { 
     // Get real and relative path for current file 
     $filePath = $file->getRealPath(); 
     $relativePath = substr($filePath, strlen($rootPath) + 1); 

     // Add current file to archive 
     $zip->addFile($filePath, $relativePath); 
    } 
} 

// Zip archive will be created only after closing object 
$zip->close(); 


header('Content-Description: File Transfer'); 
header('Content-Type: application/octet-stream'); 
header('Content-Disposition: attachment; filename='.basename($zip_file)); 
header('Content-Transfer-Encoding: binary'); 
header('Expires: 0'); 
header('Cache-Control: must-revalidate'); 
header('Pragma: public'); 
header('Content-Length: ' . filesize($zip_file)); 
readfile($zip_file); 

但是當我加載我的頁面時,什麼也沒有發生。

+0

我有一個問題 – rtfm

+0

你檢查了錯誤日誌嗎? –

+0

@KIKOSoftware我正在使用'error_reporting(E_ALL);'但沒有顯示錯誤。這只是沒有發生什麼,當我加載頁面 – Jarla

回答

0

php代碼必須位於頁面頂部。在它之前不應該有任何其他的html代碼

相關問題