zip圧縮するAPIは幾つかあるので、好みに応じて実行する。
zipファイルのサイズを取得して、HTTPレスポンスヘッダに記載する。
データサイズ分メモリ上に乗っかっても問題なければ、readfile
で良い。
問題あれば、下記のようにバッファリングして送信する。
// サンプルとして、テキストファイル2個から
// Zipファイルを作成し、HTTPレスポンスで返す
$addfile = $imgbox_temp.”test.txt”;
outputfile($addfile, “1234567890″);
$addfile2 = $imgbox_temp.”test2.txt”;
outputfile($addfile2, “aaaaa”);
$filepath = “dummy.zip”;
$zip = new ZipArchive();
// ZIPファイルをオープン
$res = $zip->open( $filepath, ZipArchive::CREATE);
if( $res == true )
{
//第2引数を省略すると、ファイルのパスディレクトリ構成になる
$zip->addFile( $addfile, “test.txt” );
$zip->addFile( $addfile2, “test2.txt” );
$zip->close();
}
// Responseヘッダを作成し、作成したZipファイルのバイナリデータを出力
header(‘Content-Disposition: attachment; filename=”‘.basename($filepath).’”‘);
header(‘Content-Type: application/octet-stream’);
header(‘Content-Transfer-Encoding: binary’);
header(‘Content-Length: ‘.filesize($filepath));
// readfile 大容量ファイルだとout of memoryになる
//readfile($filepath);
// out of memoryエラーが出る場合、出力バッファリングを無効
while (ob_get_level() > 0) {
ob_end_clean();
}
ob_start();
if ($fp = fopen($filepath, 'rb')) {
while(!feof($fp) and (connection_status() == 0)) {
echo fread($fp, '307200');
ob_flush();
}
ob_flush();
fclose($fp);
}
ob_end_clean();
deletefile( $filepath);