2011年5月26日 星期四

利用header做檔案下載控制

通常在做檔案下載功能的時候,都是做個link連結到檔案,之後跳出視窗讓使用者選擇要下載或者開啟檔案,這種方法雖然簡單方便,但是有的時候會出現其他使用者將你的連結盜連到自己的網站,消耗你的資源增加他的人氣,想要防止這種方法有許多方法,例如先將檔案丟到SQL再去SQL做存取,或是利用權限設定之類的,今天要講的方法是先將檔案交給PHP處理再丟給使用者下載的方式,來規避他人直接取得你的檔案儲存位置,使用底下這隻函數即可做到:

function dl_file($file){

//檢查檔案是否存在
if (!is_file($file)) { die("404 File not found!"); }

//取得檔案相關資料
$len = filesize($file);
$filename = basename($file);
$file_extension = strtolower(substr(strrchr($filename,"."),1));

//將檔案格式設定為將要下載的檔案
switch( $file_extension ) {
case "pdf": $ctype="application/pdf"; break;
case "exe": $ctype="application/octet-stream"; break;
case "zip": $ctype="application/zip"; break;
case "doc": $ctype="application/msword"; break;
case "xls": $ctype="application/vnd.ms-excel"; break;
case "ppt": $ctype="application/vnd.ms-powerpoint"; break;
case "gif": $ctype="image/gif"; break;
case "png": $ctype="image/png"; break;
case "jpeg":
case "jpg": $ctype="image/jpg"; break;
case "mp3": $ctype="audio/mpeg"; break;
case "wav": $ctype="audio/x-wav"; break;
case "mpeg":
case "mpg":
case "mpe": $ctype="video/mpeg"; break;
case "mov": $ctype="video/quicktime"; break;
case "avi": $ctype="video/x-msvideo"; break;
//禁止下面幾種類型的檔案被下載
case "php":
case "htm":
case "html":
case "txt": die("Cannot be used for ". $file_extension ." files!"); break;

default: $ctype="application/force-download";
}

//開始編寫header
header("Pragma: public");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: public");
header("Content-Description: File Transfer");

//使用利用 switch判別的檔案類型
header("Content-Type: $ctype");

//執行下載動作
$header="Content-Disposition: attachment; filename=".$filename.";";
header($header );
header("Content-Transfer-Encoding: binary");
header("Content-Length: ".$len);
@readfile($file);
exit;
}
?>


但是如果你只是純粹想要單純一點更改下載檔案的部份的話,只需要這樣:


$saveasname = "excel95.xls"; //要被儲存成的檔名
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; Filename="'.$saveasname.'"');
readfile($saveasname);
?>


readfile是把檔案的內容讀到網頁中,header就會把網頁內容丟到給你下載的檔案裏面,甚至如果你需要對檔案做壓縮再下載的話,可以利用:


$saveasname = "test.txt.gz";
//Header設定
header('Content-Encoding:x-gzip');
header('Content-Type: application/x-gzip');
header('Content-Disposition: attachment; Filename="'.$saveasname.'"');
header('Pragma: no-cache');
//要輸出的內容用gzencode函式處理過
echo gzencode('hi', 9);
?>


header還有許多各種不同的對網頁做控制的功能,詳情請詳閱PHP官方網站XD~
例如將上面其中的
header('Content-Type: application/x-gzip');
改成
header("Content-Type: application/force-download");
就可以讓使用者變成強制直接儲存檔案,不能讓他單純只使用預覽,等等的功能
是個非常實用的函數喔^^"

沒有留言:

張貼留言

Google Analytics初學者入門簡介