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


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('');
header('Content-Type: application/zip');
header('Content-Disposition: attachment; filename=""');
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('');
     ->setHeader('Content-Type', 'application/zip')
     ->setHeader('Content-Disposition', 'attachment; filename=""')
     ->setHeader('Content-Length', strlen($file));
//If using Zend_Layout, we need to disable it:
//Disable ViewRenderer:

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.