2016-11-16 50 views
-1

我正在使用以下代碼來隱藏真實文件路徑以防止盜鏈。每當我嘗試通過新創建的地址下載文件時,包括文件大小和文件名在內的所有內容都可以,但是當我嘗試打開文件時,無論是PDF文件還是ZIP文件,它都表示文件已損壞。隱藏真實文件路徑以防止盜鏈

當我直接從服務器下載文件時,它可以正常工作,並且沒有任何問題。

$file = 'file.pdf'; 

$path = $_SERVER['DOCUMENT_ROOT'].'/files/'; 

$file_Path = $path . $file; 

list($file_Basename, $file_Ext) = explode('.', $file); 

switch($file_Ext) 
{ 
    case "pdf": $ctype = "application/pdf"; break; 
    case "exe": $ctype = "application/octet-stream"; break; 
    case "zip": $ctype = "application/zip"; break; 
    case "rar": $ctype = "application/rar"; break; 
    case "doc": $ctype = "application/vnd.ms-word"; 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; 
    default: $ctype = "application/force-download"; 
} 

header('Content-Type:'. $ctype); 

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

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

header('Content-Disposition: attachment; filename="downloaded.pdf"'); 

readfile($file_Path); 

exit(); 

enter image description here

enter image description here

我在做什麼錯?

+0

檢查的內容在文本編輯器,看它是否真的是你希望它是什麼。 – PeeHaa

+0

@PeeHaa是的。當我通常從服務器下載文件時,它可以工作。 – Afshin

+0

@Martin沒有幫助。我仍然得到同樣的錯誤。 – Afshin

回答

0

我改變了我的代碼,增加了ob_clean()flush(),使其工作:文件的

header('Content-Type:'. $ctype); 

header('Content-Disposition: attachment; filename="'.$file->file_Name.'"'); 
header('Content-Transfer-Encoding: binary'); 

header("Content-Length: " . filesize($file_Path)); 

//This part must be added to your code 
if (ob_get_length() > 0) { 
    ob_clean(); 
    flush(); 
} 

readfile($file_Path); 

exit();