PHPでファイルをダウンロードするには

PHPを使ってユーザにファイルをダウンロードしてもらいたい場合は、header関数を使ってContent-Disposition:ヘッダを送信すれば簡単に構築できます。
今回はその方法を簡単に紹介しましょう。

まずは基本的なContent-Disposition構文は次のとおりです。
Content-Disposition: attachment; filename=”<ファイル名>”
Content-Type:<ファイル形式>

Content-Disipositionフィールドを「attachment」とすることで、ユーザに表示するか保存するかを選択させることができます。よくある開くか保存するかのダイアログボックスが表示されます。

Content-typeを設定すればファイル形式を指定できます。

ファイル形式 対応するContent-Type
HTML text/html
テキスト text/plan
CSS text/css
JPEG画像 image/jpeg
GIF画像 image/gif
PNG画像 image/x-png
PDF application/pdf
tar形式圧縮ファイル application/x-tar
zip形式圧縮ファイル application/zip
CSVファイル application/x-csv
Excelファイル application/vnd.ms-excel
その他のファイル application/octet-stream

次は、簡単なプログラムを書いてみます。


まずはCSVファイルのダウンロードです。

<?php
//ダウンロードするファイル名を指定します。
$filename = “csvfile.csv”;
header(“Content-disposition:attachment;filename=\”$filename\””);
header(“Content-type: application/x-csv”);
?>

次は、Jpeg画像をダウンロードするソースです。

<?php
//自動的にmb_ouput_handler()が呼ぶのを回避
mb_http_output(“pass”);
//ファイルの格納されいる場所を指定
$file_path = “../images”;
//ダウンロードするファイル名を指定
$filename = “jpeg_image.jpg”;
header(“Content-disposition:attachment;filename=\”$filename\””);
header(“Content-type: image/jpeg”);
header(“Contet-length: “.filesize($file_path.$filename));
readfile($file_path.$filename);
?>

間違っていたらご指摘ください。m(__)m