We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

File downloads

How to enable file download without completely buffering the file in memory?

so instead of

// insert headers here ...
$data = file_get_contents($filename);
$this->response->setContent($data);
$this->response->send()

something like

// insert headers here ...
$this->response->setRawOutputModeFunctionWhichDoesNotExist(true);
readfile($filename)


10.2k

Wait ..This seems to work.

$this->view->setRenderLevel(\Phalcon\Mvc\View::LEVEL_NO_RENDER);

$response = $this->response;
$response->setHeader("Content-Type", $mimetype);
$response->setHeader("Content-Disposition", 'attachment; filename="' . $filename . '"');
readfile($path);

I don't think that this is a good idea, because Phalcon uses ob_* caching here.



98.9k

If possible, a better and fast way is move/copy the file to the public folder and make a redirection. I'm pretty sure the web server has better and more optimal strategies to transport files of any size with less resource consumption than php.

file_put_contents($path, 'temp/' . $filename);
$this->response->redirect('temp/'. $filename);


10.0k

I do it this way. Works.

$this->view->setRenderLevel(\Phalcon\Mvc\View::LEVEL_NO_RENDER);
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header('Content-Description: File Transfer');
header('Content-type: ' . $filetype);
header('Content-length: ' . $filesize);
header('Content-Disposition: attachment; filename="'.$filename.'"');
readfile($file);
die();


2.9k

but when i use Phalcon suggestion framework show my error "You don't have access to this module" URL is "https://s745221/public/tmp/file.user" file.user - filename

Only to document on this post, there's another post that helped me with easier file response attachment:

@nini posted an useful message https://forum.phalcon.io/discussion/1306/struggling-with-response-setheader

This makes use of method setFileToSend of Request. But don't forget to send() the response after setting the file to send.

Also do $this->view->disable(); to disable views output before sending the response.