ここではPHPでExcelファイルやPDFファイルなどをダウンロードさせる方法について解説していきます。

サンプルソース
<?php
$file = 'fileName.pdf';
$fileSize = filesize($file);
header("Content-Disposition: attachment; filename={$file}");
header("Content-Length:{$fileSize}");
header("Content-Type: application/octet-stream");
readfile($file);
解説
header(“Content-Disposition: attachment; filename={$file}”); (5行目)
Content-Dispositionでダウンロードさせるファイル名を指定します。
header(“Content-Length:{$fileSize}”); (6行目)
Content-Lengthでダウンロードさせるファイルのサイズを指定します。
header(“Content-Type: application/octet-stream”); (7行目)
Content-Typeでapplication/octet-streamを指定します。
readfile($file); (8行目)
ファイルからデータを読み取ります。
こうする事でユーザーにファイルをダウンロードさせることができます。
