2016-11-16 5 views
-1

次のコードを使用して、ホットリンクを防ぐために実際のファイルパスを隠しています。新しく作成されたアドレスからファイルをダウンロードしようとすると、ファイルサイズやファイル名を含むすべてがOKですが、ファイルを開くときに、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(); 
関連する問題