2012-02-28 67 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