2012-02-28 63 views
0

下面的代碼是爲了兩個目的
1)我將一個文本文件保存在我的服務器上名爲「backup_db」的文件夾中,它的工作正常,當我打開包含所有文本文件數據我下載的txt文件是空的

2)同時我也讓這個文件可以下載給用戶,這樣他就可以爲自己下載它,並可以保存在他的硬盤上,並根據我的願望下載,但不幸的是.txt文件保存在我的硬盤,打開它的空當,我不知道爲什麼,請幫我出

//保存文件

$handle = fopen('backup_db/db-backup-'.date('d-m-Y_H-i-s').'-'.(md5(implode(',',$tables))).'.txt','w+'); 

$rr = fwrite($handle,$re); 

//fclose($handle); 

$ww = "db_backup".$rr.".txt"; 

//$handle = ""; 

header('Content-Disposition: attachment; filename=' . urlencode($ww)); 

header('Content-Type: application/force-download'); 

header('Content-Type: application/octet-stream'); 

header('Content-Type: application/download'); 

header('Content-Description: File Transfer');}} 
+1

你確定要發送正確的文件名? ('dm-Y_H-i-s')。' - '。(md5(implode(',',$ tables)))這個文件被稱爲:''backup_db/db-backup - '。 '.txt',而你發送的文件是:''db_backup「。$ rr。」。txt「'($ rr是寫入文件的字節數......) – Yaniro 2012-02-28 12:04:57

+0

是的,你是對的Yaniro先生。好吧,那麼你建議我做什麼?它會更好,如果你編輯我現有的代碼,以便我可以輕鬆地通過它 – user1210460 2012-02-28 12:11:43

+0

現在兩個文件具有相同的名稱意味着服務器上的一個和我的硬盤上的「db-backup-test」,但我仍然面臨同樣的問題 – user1210460 2012-02-28 12:16:23

回答

2

您只設置HTTP標頭,但沒有將文件寫入響應主體。使用fpassthru()readfile()將文件的內容直接寫入響應。

樣品(來自php.net截取)

<?php 
$file = 'monkey.gif'; 

if (file_exists($file)) { 
    header('Content-Description: File Transfer'); 
    header('Content-Type: application/octet-stream'); 
    header('Content-Disposition: attachment; filename='.basename($file)); 
    header('Content-Transfer-Encoding: binary'); 
    header('Expires: 0'); 
    header('Cache-Control: must-revalidate'); 
    header('Pragma: public'); 
    header('Content-Length: ' . filesize($file)); 
    flush(); 
    readfile($file); 
    exit; 
} 
?> 

順便說一句: 設置相同的標頭多次簡單的覆蓋,除非你的header()第二參數設置爲false設定前的值。

您的代碼

header('Content-Type: application/force-download'); 
header('Content-Type: application/octet-stream'); 
header('Content-Type: application/download'); 

結果如下標題:

Content-Type: application/download 
1

在標題中發送文件名只會給用戶一個建議的文件名。嘗試回顯文件的內容。

0

入住這 例如:

$filename = urlencode($fileName); //download.txt 
header("Content-Disposition: attachment; filename=\"" . $filename. "\";"); 
0

您應該添加

header("Content-Length: $size") 

其中$size是以字節爲單位YOUT文件的大小。

+0

不,你不需要。PHP會爲你做這件事。 – CodeCaster 2012-02-28 12:31:40