LoginSignup
1
1

More than 5 years have passed since last update.

リンククリックでファイルをダウンロードさせる

Posted at

これは何?

単一ファイルをリンククリックするだけでダウンロードさせたいときに使います。
セキュリティ的な考慮により、外部パラメーターでファイル名組み立て、はやってません。

コード

<?php
// ファイルパス(ドメインルートからのフルパス)
$filepath = './wp-content/DEMO.pdf';
/**
  以下は特に変更する必要はありません
 */
header('Content-Type: application/force-download');
header('Content-Disposition: attachment; filename="'.basename($filepath).'"');
header('Content-Length: '.filesize($filepath));

// out of memoryエラーが出る場合に出力バッファリングを無効
while (ob_get_level() > 0) {
    ob_end_clean();
}
ob_start();

// ファイル出力
if ($file = fopen($filepath, 'rb')) {
    while (!feof($file) and (connection_status() == 0)) {
        echo fread($file, '4096'); // 指定したバイト数ずつ出力
        ob_flush();
    }
    ob_flush();
    fclose($file);
}
ob_end_clean();
?>

デモ

元ファイル

ダウンロードリンク

※ いきなりダウンロードされますのでご注意ください
http://www.musta.jp/download.php

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1