とりあえずの備忘録

主にパソコンやインターネットに関するメモ

PHP WEBからアクセス出来ない場所のファイルをダウンロードさせる

Fedora Core 4と同時にインストールしたPHP(php.ini未編集)の環境において、WEBからアクセス出来ない場所のファイルをダウンロードさせる方法。

readfile関数を使ってダウンロードさせる

<?php
//ダウンロードファイル(WEBからアクセス出来ない場所)
$download_file = '/var/www/souko/mydata.zip';

if (file_exists($download_file)) {
 //ファイル名とファイルサイズを得る
 $filename = basename($download_file);
 $filesize = filesize($download_file);
 //ダウンロード開始
 header('Content-type: application/octet-stream');
 header('Content-disposition: attachment; filename="'.$filename.'"');
 header('Content-Length: '.$filesize);

 //出力バッファをオフ
 ob_end_flush();
 readfile($download_file);
}
?>

サイズの大きなファイルをダウンロードさせる場合、「ob_end_flush()」を手前に記述することで可能となった。