【PHP】ファイルをzipで圧縮して出力する。

めも。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
// zipクラスのインスタンスを生成
$zip = new ZipArchive();
 
// 出力時のファイル名
$outFileName = 'hoge.zip';
 
// 作業ファイルパスを生成
$tmpFilePath = tempnam(sys_get_temp_dir(), 'tmp');
 
// 作業ファイルをオープン
$result = $zip->open($tmpFilePath, ZIPARCHIVE::CREATE | ZIPARCHIVE::OVERWRITE);
if($result !== true) {
    return false;
}
 
// 圧縮するファイルを定義
$addFilePath = file_get_contents('/path/to/file.ext');
$addFileName = 'file.ext';
// zipファイルに追加(繰り返せば複数ファイル追加可能)
$zip->addFromString($addFileName , $addFilePath);
// ストリームを閉じる
$zip->close();
 
// ブラウザに出力
header('Content-Type: application/octet-stream; name="'.$outFileName.'"');
header('Content-Disposition: attachment; filename="'.$outFileName.'"');
header('Content-Length: '.filesize($tmpFilePath));
echo readfile($tmpFilePath);
// 一時ファイルを削除
unlink($tmpFilePath);
die();