在PHP中保護檔案下載位址

在PHP中,為了避免使用者直接知道要下載的檔案實際路徑,或者為了對檔案的下載權限做保護時,我們就必須在檔案下載之前寫一支中介程式來做過濾或是保護,在使用者通過某些驗證後,我們再讀取使用者所需的檔案以供下載,方式如下:

// 因我的資料庫為UTF8格式,在有中文檔名時,如不轉成BIG-5的話,IE下載回來的檔名會變亂碼...
$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);
}


2008-04-04 05:49:30

I said something before.....
Label 在 PictureBox 上背景不能透明 2021-05-24 06:32
Textbox限制輸入數字 2016-11-14 21:17
C# 字串分割 2016-07-28 20:25
LINQ筆記 2016-07-27 03:33
SQL Server的記錄檔無限成長 2015-11-02 05:47
安裝MySQL ODBC 5.2錯誤 – Error 1918 2014-02-03 19:27
在Reporting Service報表上顯示QRCode 2013-04-01 02:59
SQL Server DB管理筆記 2012-07-05 20:21
還原MSSQL遇到「備份組包含現有的XXX資料庫以外的資料庫備份」的錯誤 2012-05-15 12:35
Informix計算兩時間的差距 2010-08-12 06:01
ReportViewer顯示LocalReport及ServerReport 2010-05-24 04:13
SQL Server取得當月第一天及最後一天 2010-01-19 00:00
簡單的對DataTable做Distinct 2009-09-20 22:18
使用 svcutil 編譯 WCF 錯誤解法 2009-07-09 07:59
PHP加載MSSQL函式庫 2008-10-20 08:54