2012-02-19 132 views
2

我正在嘗試創建一個強制下載頁面,以防止瀏覽器打開應該下載的文件。問題是下載的文件有0個字節,因此無法使用。我的代碼有什麼問題?強制在php下載

$file = "http://gh0stsec.zxq.net/background1.jpg"; 
header("Pragma: public"); 
header("Expires: 0"); 
header("Cache-Control: must-revalidate, post-check=0, pre-check=0"); 
header("Content-Type: application/force-download"); 
header("Content-Disposition: attachment; filename=".basename($file)); 
header("Content-Transfer-Encoding: binary"); 
header("Content-Length: ".filesize($filename)); 
header("Content-Description: File Transfer"); 
@readfile($file); 
exit(); 
+0

'應用程序/強制下載'是不是一個真正的MIME類型。它被推遲了。這不是觸發下載的原因。它只是'Content-Dispositon'。添加無效的MIME類型毫無意義。 – mario 2012-02-19 15:21:00

回答

3

檢查:

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

我覺得應該是:

header("Content-Length: ".filesize($file)); 
+0

謝謝!馬上解決它。我不知道我是如何忽略這一點的。 – 2012-02-19 15:05:24

1

我認爲你將有一個問題與filesize因爲它不是一個本地文件(如果它是,使用相對路徑)。 Content-Type標題對我來說總是有些奇怪,但在我讀的所有示例中,force-download始終是一個後備。無論如何,我這樣做,它似乎工作:

<?php 
$file = file_get_contents('http://gh0stsec.zxq.net/background1.jpg'); 

if ($file) 
{ 

    header('Content-Description: File Transfer'); 
    header('Content-Type: application/octet-stream'); 
    header('Content-Disposition: attachment; filename=background1.jpg'); 
    header('Content-Transfer-Encoding: binary'); 
    header('Expires: 0'); 
    header('Cache-Control: must-revalidate'); 
    header('Pragma: public'); 
    header('Content-Length: ' . strlen($file)); 
    ob_clean(); 
    flush(); 

    echo $file; 
} 
else 
{ 
    echo 'error'; 
} 
?>