// download.php
<?php
require_once 'file.func.php';
$filename = $_GET['filename'];
down_file($filename);
// file.func.php中的下載函數
function down_file(string $filename, $allowDownExt=['png','jpg','jpeg','gif','txt','html','tar','zip']) {
// 檢測下載文件是否存在并可讀
if (!is_file($filename)) {
return false;
}
// 檢測文件類型是否允許下載
$ext = strtolower(pathinfo($filename,PATHINFO_EXTENSION));
if (!in_array($ext,$allowDownExt)) {
return false;
}
// 通過heander()發送頭信息
// 告訴瀏覽器輸出的是字節流
header('content-type:application/octet-stream');
// 告訴瀏覽器返回的文件大小是按照字節計算的
header('Accept-Ranges:bytes');
// 告訴瀏覽器返回的文件大小
header('Accept-Length:'.filesize($filename));
// 告訴瀏覽器如何處理文件(這里是作為附件處理), 告訴瀏覽器最終下載完的文件名稱
header('Content-Disposition:attachment:filename=Daniel_'.basename($filename));
// 讀取文件中的內容
readfile($filename);
exit;
}
錯誤出現在
Disposition:attachment:filename=Daniel_'.basename($filename));
attachment 后面應該是分號而不是冒號, 因為這個錯誤下載的文件名是'download.php', 內容是tar文件里面內容的字節流形式
真是新手錯誤TAT