1. Home
  2. Archive
  3. PHPで出力ファイルをダウンロード形式にする

PHPで出力ファイルをダウンロード形式にする

PHPの出力をダウンロード形式にするにはheader()でContent-Typeを指定してreadfile()で出力します。コードは下記のような感じ。

<?php
$file = "test.txt";
header("Content-type: text/plain");
header("Content-Disposition: attachment; filename=$file");
readfile($file);
?>

このコードを実行すると「ダウンロードしますか?」のウインドウが開きます。この例ではテキストファイルなのでContent-Typeは「text/plain」になっていますが、ファイルの種類によってContent-Typeは様々です。

主なContent-Type一覧
ファイル形式 Content-Type
HTML text/html
PLAIN テキスト text/plain
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/vnd.ms-powerpoint

まだまだ沢山ありますが、実際使用するのはこのくらいかなと。下記にContent-Typeの一覧が載っています。

Content-Type一覧

コメントフォーム

※HTMLタグは使用できません。