2012-08-10 49 views
1

我試圖在下載文件之前用PHP顯示HTML頁面。我知道我不能重定向到一個不同的頁面並同時下載一個文件,但爲什麼這不起作用?PHP不會顯示頁面並下載

echo "<html>...Example web page...</html>"; 

$download = '../example.zip'; //this is a protected file 

header('Content-Type: application/zip'); 
header('Content-Disposition: attachment; filename=example.zip'); 
readfile($download); 

文件下載,但它從不顯示回顯的HTML頁面。但是如果我刪除下載,頁面顯示。

+2

打印內容後無法發送自定義標題。 – 2012-08-10 03:04:28

+0

@navnav謝謝。你推薦我做什麼? – 2012-08-10 03:05:56

+0

啊,所以你不希望他們看到文件路徑? – 2012-08-10 03:19:16

回答

0

因爲你可以推定製標題之前不能輸出任何東西,我會建議使用JS重定向到下載,這通常讓你在同一頁上(只要你只是處理壓縮的內容,沒有別的)。

所以,試試這個:

$download = 'example.zip'; 

echo '<head> <script type="text/javascript"> function doRedirect(){window.location = "'.$download.'"}</script> 

</head><html><script type="text/javascript"> doRedirect() </script> <...Example web page...</html>'; 

或者,如果你需要它的計時器:

echo '<head> <script type="text/javascript"> function doRedirect(){window.location = "'.$download.'"}</script> 

</head><html><script type="text/javascript"> 
setTimeout(doRedirect(),1000);//wait one second</script> <...Example web page...</html>'; 

編輯:

如果你想隱藏的文件路徑,我會建議製作一個下載腳本,JS將重定向到。

所以基本上,要做你正在做的事情,然後用JS指出它。像這樣:

下載。PHP:

//use an ID or something that links to the file and get it using the GET method (url params) 

    $downloadID = $_GET['id']; 

    //work out the download path from the ID here and put it in $download 
if ($downloadID === 662) 
{ 
    $download = 'example.zip';//... 
} 
    header('Content-Type: application/zip'); 
    header('Content-Disposition: attachment; filename=$download'); 
    readfile($download); 

,然後在主HTML文件,使用JS指向它,用正確的ID:

<head> <script type="text/javascript"> function doRedirect(){window.location = "Download.php?id=662"}</script> 

</head><html><script type="text/javascript"> doRedirect() </script> <...Example web page...</html> 
0

有一個簡單的原則:

記住頭之前任何實際產量 發送,無論是普通的HTML標記,空行的文件,或者從PHP()必須被調用。

解決方案是準備兩個頁面,一個用於顯示HTML內容,一個用於下載。

在頁面1中,使用javascript設置一個定時器,在幾次之後重定向到下載鏈接。例如,「5秒後,下載將開始。」

1

將內容發送到瀏覽器後,您不能set header information。如果你真的得到下載 - 可能有一些輸出緩存在某個地方。

對於你要完成什麼,你可能想顯示HTML內容,並使用<meta>標籤或JavaScript重定向到下載腳本。我相信大多數瀏覽器將開始下載,同時保持用戶可以看到上次加載的頁面(實際上應該是你想要做的)。

<meta http-equiv="refresh" content="1;URL='http://example.com/download.php'"> 

或者:

<script type="text/javascript"> 
    window.location = "http://example.com/download.php" 
</script> 
0

正如已經說過,你不能發送標題後輸出已經發送。

所以,這可能會爲你工作:

header('Refresh: 5;URL="http://example.com/download.php"'); 
header('Content-Type: application/zip'); 
header('Content-Disposition: attachment; filename=example.zip'); 
readfile($download); 

http-equiv<meta http-equiv="refresh"意味着namevalue當量 alent到HTTP標頭,所以它做同樣的事情的Refresh:頭。

SourceForge下載任何文件,您將看到一個JavaScript實現(Your download will start in 5 seconds...)。