2016-08-15 38 views
0
<?php 
include "function.php"; 

$account = findSomeFile(); 
$file_url = '/var/www/html/tvconfig/netflix/'.$account.'.zip'; 
echo $account; 

header('Content-Type: application/octet-stream'); 
header("Content-Transfer-Encoding: Binary"); 
header("Content-disposition: attachment; filename=\"" . basename($file_url) . "\""); 
readfile($file_url); 

?> 

以上是我的PHP腳本。當我加載頁面時,我在瀏覽器中獲得下載提示,但頁面上沒有回顯。我試過在readfile函數後面放置echo,但它不起作用。是否可以創建一個強制文件下載並回顯字符串的PHP頁面?

+3

沒有,因爲單個HTTP請求只能有單個HTTP響應;下載和回聲將是兩個響應 –

+1

如果您希望它的工作方式與此類似,可以從一個頁面到下載頁面發出AJAX請求。然後,它會下載該文件,您將保持在同一頁面上。因此,例如,您可以創建另一個HTML頁面,在那裏您將寫入「您的下載已開始」等內容,同時向頁面發出AJAX請求。 – Janno

+1

而且,發出後,回聲您的標題將沒有任何區別 –

回答

2

你可以玩一個小竅門:

<?php 
$account = "38950596"; 
$file_url = "$account.json"; 
echo "Hello Friend!\n"; 

$fc = file_get_contents($file_url); 
?> 
<script type="text/javascript"> 
window.onload = function(e) { 
    var pom = document.createElement('a'); 
    pom.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent('<?php echo $fc ?>')); 
    pom.setAttribute('download', '<?php echo $account ?>'); 
    pom.click(); 
} 
</script> 

這將創建一個錨元素,只要頁面加載時,它會通過使用點擊事件迫使文件下載。

演示:http://main.xfiddle.com/e1a35f80/38950596_stackoverflow.php

+0

只要你的文件大於幾兆字節這個代碼將導致你的服務器內爆,也許客戶端... – deceze

+0

@deceze OP反正會使用readfile($ file_url);那麼它將如何改變? –

+0

'readfile'直接從磁盤流到輸出; 'file_get_contents'首先將文件全部讀入內存。 – deceze

相關問題