user309349
user309349

Reputation: 21

How to calculate Content-Length for a file download within Kohana PHP?

I'm trying to send a file from within a Kohana model to the browser, but as soon as I add a Content-Length header, the file doesn't start downloading right away.

Now the problem seems to be that Kohana is already outputting buffers. An ob_clean at the begin of the script doesn't help this though. Also adding ob_get_length() to the Content-Length isn't helping since this just returns 0. The getFileSize() function returns the right number: if I run the script outside of Kohana, it works.

I read that exit() still calls all destructors and it might be that something is outputted by Kohana afterwards, but I can't find out what exactly.

Hope someone can help me out here...

This is the piece of code I'm using:

public function download() {
        header("Expires: ".gmdate("D, d M Y H:i:s",time()+(3600*7))." GMT\n");
        header("Content-Type: ".$this->getFileType()."\n");
        header("Content-Transfer-Encoding: binary\n");
        header("Last-Modified: " . gmdate("D, d M Y H:i:s",$this->getCreateTime()) . " GMT\n");
        header("Content-Length: ".($this->getFileSize()+ob_get_length()).";\n");
        header('Content-Disposition: attachment; filename="'.basename($this->getFileName())."\"\n\n");
        ob_end_flush();

        readfile($this->getFilePath());
        exit();
}

Upvotes: 2

Views: 2093

Answers (3)

Chris Gilley
Chris Gilley

Reputation: 1

In 3.1 and forward, use

Request::current()->response()->send_file(FILENAME);

Took me some digging so hopefully this helps someone

Documentation

Upvotes: 0

alex
alex

Reputation: 490263

There is a much simpler way to send a file with Kohana. If you are using Kohana 2.x it's done like this...

download::force('./application/downloads/file.txt');

Documentation

If you are using Kohana 3.x, it is done like this...

$this->request->send_file('./application/downloads/file.txt');

Documentation

Upvotes: 4

user309349
user309349

Reputation: 21

Found out I needed to call Kohana::close_buffers(FALSE) to clear Kohana's output buffer. It was a long search, but now it works.

Upvotes: 0

Related Questions