HTMLの a タグのリンク先にPHPプログラムを指定してファイルをダウンロードする方法ですが、 リンクファイルの引数を GET 指定する様にします。 
HTMLのソースは以下の様にします。 リンクファイルの引数を file として、その値にファイル名を直接指定しています。 
呼出すPHPプログラムは download.php とします。 
<!doctype html> <html lang="ja"> <head> <meta charset="utf-8"> </head> <body> <h1>ファイルダウンロード</h1> <br /> <a href="./download.php?file=test.txt">ファイルダウンロード(test.txt)</a> </body> </html>
PHPプログラムは以下の通りです。
<?php
//指定ファイル名
if(!isset($_GET['file'])){
    exit();
}
$fileName = $_GET['file'];
//ヘッダ
header('Content-Type: application/force-download');
//ダイアログボックスの表示ファイル名
header('Content-Disposition: attachment; filename="'.basename($fileName).'"');
header('Content-Transfer-Encoding: binary');
header('Content-Length: '.filesize($fileName));
header('X-Download-Options: noopen');
//出力バッファの無効化
while (ob_get_level()) {
  ob_end_flush();
}
flush();
//ファイル出力
readfile($fileName);
?>
いろんなサイトを見ると、 出力ヘッダのタイプは application/force-download でOKな様です。 
ファイル出力は readfile() で行います。
PR
 
  
コメント