使用PHP中的fopen下载文件时出现问题

时间:2016-03-30 06:20:08

标签: php file download

我想用fopen下载一个sql文件,我的问题是下面的代码除了html文件之外还会下载整个sql文件,如下所示:

<!DOCTYPE html>
...

<span style=\"font-family:tahoma,arial,helvetica,sans-serif\">sth</span></p>
\n","media/images/","media/images/","0","en","1","0","2000-11-30","admin","sth","0","2000-12-13 00:00:00","0","","","","","12","","","","0","","73","1","1","1","1","1","1","1","1","1","1","1","1","1","0","0","0","","","","","0","");
INSERT INTO sctp_contents VALUES("458","","books ","","<html>

代码:

header("Content-type: " . 'application/octet-stream');
header("Content-Disposition: attachment; filename=/backup/".$db_bkup);
header("Content-Transfer-Encoding: binary");
header("Content-length: $file_size");

while(!feof($handle)) {
    echo fread($handle, $file_size);
    flush();
}
fclose($handle);
die;

帮助我,谢谢

1 个答案:

答案 0 :(得分:0)

将其余的代码拼凑成一个可读的格式我看不出任何特别看起来不对的东西 - 对我而言,唯一看起来奇怪的是jDateTime〜这可能是一个后来的函数PHP版本或自定义函数我不知道,但它看起来很奇怪。

除此之外,可能使用ob_clean确保在开始下载并使用正确的标题之前没有输出字符。

ob_clean();
header("Content-Type: application/octet-stream");
header("Content-Disposition: attachment; filename=/backup/{$db_bkup}");
header("Content-Transfer-Encoding: binary");
header("Content-Length: {$file_size}");

while( !feof( $handle ) ) {
    echo fread( $handle, $file_size );
    flush();
}
fclose( $handle );
die;