2015-08-23 48 views
0

我是一位新的PHP程序員。我正在嘗試編寫代碼以允許用戶從我的網站下載文本文件。我跟蹤了關於這個問題的類似問題的答案,並將以下測試程序放在一起。它沒有強制下載文件,而是將內容發送到屏幕上(在Chrome,IE,Firefox中)。有人能指出我做錯了什麼嗎?php中的文本文件下載代碼

這裏是我的測試代碼:

<?php 
    $file = "test.txt"; 

    if(!file_exists($file)) die("I'm sorry, the file doesn't seem to exist."); 

    $type = filetype($file); 
    // Send file headers 
    header("Content-type: $type"); 
    header("Content-Disposition: attachment;filename=\"test.txt\""); 
    header("Content-Transfer-Encoding: binary"); 
    header('Pragma: no-cache'); 
    header('Expires: 0'); 
    // Send the file contents. 
    set_time_limit(0); 
    readfile($file); 
    exit(); 

?> 
+0

測試代碼沒有顯示出來。我會再試一次: – rhou

+0

<?php $ file =「../op/geneComp/upload/test.txt」; if(!file_exists($ file))die(「對不起,該文件似乎不存在。」); $ type = filetype($ file); //發送文件頭文件 header(「Content-type:$ type」); header(「Content-Disposition:attachment; filename = \」test.txt \「」); header(「Content-Transfer-Encoding:binary」); header('Pragma:no-cache'); header('Expires:0'); //發送文件內容。 set_time_limit(0); readfile($ file); \t exit(); \t ?> – rhou

+0

您的問題下方有一個「編輯」鏈接。您可以單擊它並將缺少的代碼添加到問題中,而不是添加註釋。 –

回答

0

您可以簡單地使用

$handle = fopen("file.txt", "w"); 
fwrite($handle, "Shadow "); 
fclose($handle); 

header('Content-Type: application/octet-stream'); 
header('Content-Disposition: attachment; filename='.basename('file.txt')); 
header('Expires: 0'); 
header('Cache-Control: must-revalidate'); 
header('Pragma: public'); 
header('Content-Length: ' . filesize('file.txt')); 
readfile('file.txt'); 
exit; 

編輯,嘗試單一的PHP頁面上。

+0

謝謝你的回覆。我嘗試了這個建議,但內容仍然顯示在屏幕上。還有什麼是錯的? – rhou

+0

它的工作正常。嘗試在一個單一的PHP頁面上,然後你可以明白,你有另一個問題。 –

+0

我只是複製你的代碼,並在Chrome 44.0 ....和IE11上運行它。兩人都去了屏幕。是的,我確實有另外一個問題,但我不知所措。你有什麼建議嗎? – rhou

0

此代碼將顯示在屏幕上的文本文件的內容,用戶可以下載它作爲一個文本純文本文件:

$file = "test.txt"; 

if(!file_exists($file)) die("I'm sorry, the file doesn't seem to exist."); 

$type = filetype($file); 
// Send file headers 
header("Content-type: $type"); 
header('Pragma: no-cache'); 
header('Expires: 0'); 
// Send the file contents. 
set_time_limit(0); 
echo file_get_contents($file); 

但這個代碼(由@Drop暗影)將迫使瀏覽器中顯示下載對話框不顯示任何東西:

$file = "test.txt"; 

if(!file_exists($file)) die("I'm sorry, the file doesn't seem to exist."); 

$type = filetype($file); 
// Send file headers 
header("Content-type: $type"); 
header("Content-Disposition: attachment;filename=\"test.txt\""); 
header("Content-Transfer-Encoding: binary"); 
header('Pragma: no-cache'); 
header('Expires: 0'); 
// Send the file contents. 
set_time_limit(0); 
readfile($file); 
exit(); 
+0

Drop Shadow的PHP代碼應該可以工作,但我懷疑我的系統還有其他問題導致輸出緩衝區沒有將其發送到文件,而只是顯示在屏幕上。我不知道,我希望有人可能會有一些建議。 – rhou