开发者

Files not having any content in after a header() download

I'm trying to create a download so that a user clicks on "down" it downloads a certain file from their account to their computer, I'm currently using this:

header('Content-Disposition: attachment; filename=' . basename("users/$username/$file_folder/$file_name"));
header("Content-Type:" .$file_type);
header("Content-Description: File Transfer");
header("Cache-control: private");
header("Connection: close");
header("Content-Leng开发者_开发知识库th: ".$file_size);

The problem is, the file is downloading, but it's just empty, there is no content in the file

The code before this is just an if() and a while loop with database records. Thanks in advance.


You are missing something like below: (unless the file is very large, in which case you would chunk it out)

$filename = 'path/to/file/file_name.txt';

echo file_get_contents($filename);

Alternatively you could populate a variable with the data you want put out into the file and simple echo it out like so:

$data = "begin\n";
$data .= "first line\n";
$data .= "another line\n";
$data .= "last line";

echo $data;

The content would be put out there AFTER your headers. Hope this helps.


The file is empty, because you never output the file. These header calls are just the header, you still need a body for a file to be correctly downloaded. You can use file_get_contents to echo the file contents.

header('Content-Disposition: attachment; filename=' . basename("users/$username/$file_folder/$file_name"));
header("Content-Type:" .$file_type);
header("Content-Description: File Transfer");
header("Cache-control: private");
header("Connection: close");
header("Content-Length: ".$file_size);

// echo the file, this will make the download work
echo file_get_contents("users/$username/$file_folder/$file_name"); 


after you send the headers you need to actually push out the file content...

see this http://php.net/manual/en/function.file-put-contents.php

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜