PHP管制檔案下載的方式

在許多時候,我們會不希望網友知道網址空間直接下載檔案,或是透過帳號密碼的管控才能下載時,該如何用程式做過濾及管制呢?

header("Content-type:application");
header("Content-Disposition: attachment; filename=file_name");
//file_name是預設下載時的檔名,可使用變數。
readfile("file");
//file是實際存放在你硬碟中要被下載的檔案,可使用變數。
exit(0);

header('Content-Type: application/pdf');
header('Content-Disposition: attachment; filename="downloaded.pdf"');
readfile('original.pdf');
//限制下載速度,使用 while 迴圈加上 sleep。

while (!feof($handle)) {
echo fread($handle, 8192);
sleep(1);
}

$content = "";
$fp = fopen("http://file-to-download.com/a-file.zip", "rb");

if (!$fp)
die("Error opening file.");
while (!feof($fp))
$content .= fread($fp, 2048);
fclose($fp);

$fp=fopen("local-file-name.zip", "w");
fwrite($fp, $content);
fclose($fp);

$OrgFileName = mb_convert_encoding($OrgFileName, 'BIG-5','UTF-8');

$real_path = dirname(__FILE__).'/upload/'.$FileName;

header('Pragma: public');

header('Expires: 0');

header('Cache-Control: must-revalidate, post-check=0, pre-check=0');

header('Cache-Control: public', false);

header('Content-Description: File Transfer');

header('Accept-Ranges: bytes');

// application/force-download 為通用類型,亦可判斷檔案格式做改變

header('Content-Type: application/force-download');

header('Content-Length: '.filesize($real_path));

header('Content-Transfer-Encoding: binary');

// 注意「"」不可省略,否則FireFox會無法正確讀取

header('Content-Disposition:attachment;filename="'.$OrgFileName.'"');

// 讀取來源檔案資料

if ($stream = fopen($real_path, 'rb')){

while(!feof($stream) && connection_status() == 0){

echo(fread($stream,1024*8));

flush();

}

fclose($stream);

}

header('Content-type:application/force-download'); //告訴瀏覽器 為下載
header('Content-Transfer-Encoding: Binary'); //編碼方式
header('Content-Disposition:attachment;filename='.$filename); //檔名
@readfile($filename);

作者: 林壽山

目前任職於軟體公司研究開發部門,擔任專業處長,專注於.NET C# 開發,並具備豐富的POS 收銀系統與金流整合開發經驗。我精通各類支付系統的設計與開發,包含第三方支付(如綠界、藍新、歐付寶、速買配、馬來西亞 ePay/HappyPay、台新 One 碼)、行動支付(悠遊卡、一卡通、支付寶、微信支付、街口支付)、以及信用卡支付(聯合信用卡)。 熟悉多種開發技術,擅長PHP 網頁開發(CodeIgniter、Laravel 框架)、Delphi 程式設計、資料庫設計、C# WinForm/WebForm 應用開發、ASP.NET MVC、API 串接設計,並具備LINE 串接開發的豐富經驗。 除了技術開發之外,我也熱衷於技術分享,曾擔任台中學校產業學院講師 5 年,培育新一代的軟體開發人才,致力於推動軟體技術的應用與創新。 我對技術充滿熱忱,始終保持學習與探索的心態,期望透過軟體開發為企業與社會創造更大的價值。