エントリー

PHPでファイルダウンロード

自分用にメモ。

画像やテキストファイルへ普通にリンクすると、クリックしたときに画像やテキストファイルがブラウザ内に表示されます。
以下は圧縮ファイルをダウンロードするときのように、保存先を聞いてくれるようにする方法。

<?php

$image_file = 'sample.gif';

header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename=' . $image_file);
header('Content-Length:' . filesize($image_file));
header('Pragma: no-cache');
header('Cache-Control: no-cache');
readfile($image_file);
exit;

?>

こんなコードを書いたPHPファイルへリンクすると、sample.gif のダウンロードダイアログが開きます。sample.gif はあらかじめアップロードしておきます。画像以外のファイルも同じ方法でOK。また、

<?php

$text_file   = 'sample.txt';
$text_buffer = 'テストメッセージです。';

header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename=' . $text_file);
header('Content-Length:' . strlen($text_buffer));
header('Pragma: no-cache');
header('Cache-Control: no-cache');
echo $text_buffer;
exit;

?>

こんなコードを書いたPHPファイルへリンクすると、sample.txt のダウンロードダイアログが開きます。sample.txt の内容はPHPで動的に作成します。

ページ移動

ユーティリティ

カテゴリー

検索

エントリー検索フォーム
キーワード

過去ログ

過去ログ表示フォーム
キーワード

Feed