Aiden Ryan
Aiden Ryan

Reputation: 845

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-Length: ".$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.

Upvotes: 1

Views: 112

Answers (3)

Adam Culp
Adam Culp

Reputation: 500

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.

Upvotes: 2

gen_Eric
gen_Eric

Reputation: 227220

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"); 

Upvotes: 1

David Chan
David Chan

Reputation: 7505

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

Upvotes: 0

Related Questions