2017-10-06 2 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コードはありません。

関連する問題