NYCPHP Meetup

NYPHP.org

[nycphp-talk] NEW PHundamentals Question - Headers & Downloads

Dan Cech dcech at phpwerx.net
Tue Oct 12 17:56:52 EDT 2004


Jeff Siegel - PHundamentals wrote:
> For the next PHundamentals article, we are exploring best practices in 
> the use of headers.  Over the next few weeks, we'll be asking about the 
> various ways in which headers are used.  This week's question (see 
> below) concerns the use of headers which force downloads.

I have used this combination of headers with pretty good success:

Given an array containing the details of the file like:

$attach = array(
   'filename' => 'myfile.pdf',
   'mimetype' => 'application/pdf',
   'content'  => 'pdf here'
);

header('Content-Disposition: attachment; filename='. $attach['filename']);
header('Content-length: '. strlen($attach['content']));
header('Content-type: '. $attach['mimetype']);
echo $attach['content'];
exit;

The Content-Disposition header tells the browser to open the download 
dialog, and lets it know the correct filename/extension.

The Content-length header allows the browser to display a meaningful 
progress bar.

The Content-type header lets the browser correctly display an indication 
of the file type to the user (PDF,XLS,EXE etc).  In most browsers it 
will also influence the default action (open vs download).

For some files (pdf mostly) it can be a good idea to use a different 
Content-Disposition header, namely:

header('Content-Disposition: inline; filename='. $attach['filename']);

In most browsers this will result in the pdf file being opened within 
the browser window.

I have a bunch more information regarding the use of headers for cache 
control...but that wasn't what you were asking was it ;)

Dan Cech



More information about the talk mailing list