PHP tip: How to make a file downloadable through your script

Tags:

This seems to be a relatively common question on #zftalk nowadays, so here’s a quick wrapup!

The traditional plain-PHP way

$file = file_get_contents('some.zip');
header('Content-Type: application/zip');
header('Content-Disposition: attachment; filename="some.zip"');
header('Content-Length: ' . strlen($file));
echo $file;

The Zend Framework controller way

//this is inside an action in one of your controllers:
$file = file_get_contents('some.zip');
 
$this->getResponse()
     ->setBody($file)
     ->setHeader('Content-Type', 'application/zip')
     ->setHeader('Content-Disposition', 'attachment; filename="some.zip"')
     ->setHeader('Content-Length', strlen($file));
 
//If using Zend_Layout, we need to disable it:
$this->_helper->layout->disableLayout();
 
//Disable ViewRenderer:
$this->_helper->viewRenderer->setNoRender(true);

In closing

As mentioned in the comments, this approach may not be suitable especially if you deal with very large files. I recommend checking out this post about using mod_xsendfile with PHP, as it solves the issues associated with sending files “manually” through PHP.