views:

247

answers:

2

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();
}
A: 

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.

+1  A: 

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

Docs

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

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