PHP實現文件安全下載
程序如下:
$file_name = "info_check.exe";
$file_dir = "/public/www/download/";
if (!file_exists($file_dir . $file_name)) { //檢查文件是否存在
echo "文件找不到";
exit;
} else {
$file = fopen($file_dir . $file_name,"r"); //打開文件
//輸入文件標簽
Header("Content-type: application/octet-stream");
Header("Accept-Ranges: bytes");
Header("Accept-Length: ".filesize($file_dir . $file_name));
Header("Content-Disposition: attachment; filename=" . $file_name);
//輸出文件內容
echo fread($file,filesize($file_dir . $file_name));
fclose($file);
exit;}
而如果文件路徑是"http"或者"ftp"網址的話,則源代碼會有少許改變,程序如下:
$file_name = "info_check.exe";
$file_dir = "www.easycn.net/";
$file = @ fopen($file_dir . $file_name,"r");
if (!$file) {
echo "文件找不到";
} else {
Header("Content-type: application/octet-stream");
Header("Content-Disposition: attachment; filename=" . $file_name);
while (!feof ($file)) {
echo fread($file,50000);
}
fclose ($file);
}
這樣就可以用PHP直接輸出文件了